我想理解为什么当我冻结一个模拟类而不是模拟接口时我的测试失败了
[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 /如果我使用’注入’而不是冻结,它可以工作:
[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
最佳答案 MyWebRequest是一个具体的(非抽象)类,而AutoFixture.AutoMoq不会使用Moq创建它们.这是设计的,因为AutoFixture内核已经处理了“普通”类的创建.
You can change this behaviour如果你愿意的话.但是,我经常认为必须这样做一个设计气味.但是,在这种情况下很难说,因为你已经很好地将问题减少到最小的重复.但问题是,如此处所示,MyService不会添加任何值.我确定这不是你的真实代码的样子,但由于我无法猜出你的真实代码是什么样的,我无法分辨出更好的设计是否可行.