I'd like to understand why my test fails when I'm freezing a mocked class instead of an mocked interface
[Fact]
public void MethodeName()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var webRequestMock = fixture.Freeze<Mock<MyWebRequest>>(); // freezing a class + setuping a return value
webRequestMock.Setup(a => a.GetData())
.Returns("Foo");
var myService = fixture.Create<MyService>();
var actual = myService.GetData();
webRequestMock.Verify(a => a.GetData(), Times.Once()); // Failed it's never called once
Assert.Equal("Foo", actual); // Failed, if we comment previous line, 'actual' value is always empty
}
public class MyService
{
private readonly MyWebRequest _request;
public MyService(MyWebRequest request)
{
_request = request;
}
public string GetData()
{
var data = _request.GetData();
return data;
}
}
public class MyWebRequest
{
public virtual string GetData() // you can see here, the method is well virtual, and should be overridable by moq.
{
return string.Empty;
}
}
1/ If I try with a mocked interface, it works.
[Fact]
public void MethodeName()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
const string expected = "Foo";
var webRequestMock = fixture.Freeze<Mock<IMyWebRequest>>();
webRequestMock.Setup(a => a.GetData())
.Returns("Foo");
var myService = fixture.Create<MyService>();
var actual = myService.GetData();
webRequestMock.Verify(a => a.GetData(), Times.Once()); // Success
Assert.Equal(expected, actual); // Success
}
public class MyService
{
private readonly IMyWebRequest _request;
public MyService(IMyWebRequest request)
{
_request = request;
}
public string GetData()
{
var data = _request.GetData();
return data;
}
}
public interface IMyWebRequest
{
string GetData();
}
public class MyWebRequest : IMyWebRequest
{
public virtual string GetData()
{
return string.Empty;
}
}
2/ If I use 'inject' instead of freeze, it works:
[Fact]
public void MethodeName()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
const string expected = "Foo";
var webRequestMock = new Mock<MyWebRequest>();
webRequestMock.Setup(a => a.GetData()).Returns("Foo");
fixture.Inject(webRequestMock.Object);
var myService = fixture.Create<MyService>();
var actual = myService.GetData();
webRequestMock.Verify(a => a.GetData(), Times.Once()); // Success
Assert.Equal(expected, actual); // Success
}
public class MyService
{
private readonly MyWebRequest _request;
public MyService(MyWebRequest request)
{
_request = request;
}
public string GetData()
{
var data = _request.GetData();
return data;
}
}
public class MyWebRequest
{
public virtual string GetData()
{
// make WebRequest
return string.Empty;
}
}
My autofixture version: 3.6.5.0