我想了解为什么在我冻结模拟类而不是模拟界面时我的测试失败
[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 / 如果我尝试使用模拟界面,则可以正常工作。
[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 / 如果我使用&#39;注入&#39;而不是冻结,它的工作原理:
[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;
}
}
我的自动混合版本:3.6.5.0
答案 0 :(得分:2)
MyWebRequest
是一个具体的(非抽象)类, AutoFixture.AutoMoq 不会使用 Moq 创建它们。这是按设计,因为 AutoFixture 内核已经处理了&#39; normal&#39;类。
You can change this behaviour如果您愿意的话。但是,我经常考虑不得不这样做一个设计气味。但是,在这种情况下很难说,因为你已经很好地将问题减少到最小的重复。但问题是,如此处所示,MyService
不会添加任何值。我确定这不是你的真实代码的样子,但由于我无法猜出你的真实代码是什么样子,我无法判断一个更好的设计是否可行。