I have a mock. This mock has two methods, MethodA() and MethodB(). I want to setup both methods to return false. I created various versions of the code, all of them should work, but some don't:
These work:
1.
var mock = fixture.Freeze<Mock<MyInterface>>();
mock
.Setup(m => m.MethodA(It.IsAny<T>(), It.IsAny<T>()))
.ReturnsAsync(false);
mock
.Setup(m => m.MethodB(It.IsAny<T>(), It.IsAny<T>()))
.ReturnsAsync(false);
var sut = fixture.Create<MySut>();
sut.Do(); // Calls MethodA() and MethodB() - Both return false, works
2.
var mock = new Mock<MyInterface>();
mock.SetReturnsDefault(Task.FromResult(false));
fixture.Inject(mock);
var sut = fixture.Create<MySut>();
sut.Do(); // Calls MethodA() and MethodB() - Both return false, works
3.
var mock = new Mock<MyInterface>();
mock.SetReturnsDefault(Task.FromResult(false));
fixture.Inject(mock.Object);
var sut = fixture.Create<MySut>();
sut.Do(); // Calls MethodA() and MethodB() - Both return false, works
These don't:
4.
var mock = fixture.Freeze<Mock<MyInterface>>();
mock.SetReturnsDefault(Task.FromResult(false));
var sut = fixture.Create<MySut>();
sut.Do(); // Calls MethodA() and MethodB() - MethodA returns true, fails
5.
var mock = fixture.Create<Mock<MyInterface>>();
mock.SetReturnsDefault(Task.FromResult(false));
fixture.Inject(mock);
var sut = fixture.Create<MySut>();
sut.Do(); // Calls MethodA() and MethodB() - MethodA returns true, fails
6.
var mock = fixture.Create<Mock<MyInterface>>();
mock.SetReturnsDefault(Task.FromResult(false));
fixture.Inject(mock.Object);
var sut = fixture.Create<MySut>();
sut.Do(); // Calls MethodA() and MethodB() - MethodA returns true, fails
Based on results, it seems the culprit is the Fixture.Create() method*. For some reason, if the mock is created using fixture.Create() instead of new keyword, it will not keep the configuration I set up using SetReturnsDefault(), even if the mock is frozen (meaning Fixture.Inject() was called on it). Can someone explain why?
Footnote:
* Fixture.Create() is also called internally when you call Fixture.Freeze() - Freeze is just a shorthand for a call to Fixture.Create() followed by Fixture.Inject()
Therefore, these two snippets are equivalent:
var mock = fixture.Freeze<Mock<MyInterface>>();
-
var mock = fixture.Create<Mock<MyInterface>>();
fixture.Inject(mock);