下面是我目前遇到的问题的一个最小示例:
using System.Net.WebSockets;
using AutoFixture;
using AutoFixture.AutoMoq;
using FluentAssertions;
using Xunit;
...
[Fact]
public void Test1()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization() { ConfigureMembers = true });
var sut = fixture.Create<WebSocket>();
sut.Should().NotBeNull();
}
[Fact]
public void Test2()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization() { ConfigureMembers = true });
var sut = new Mock<WebSocket>().Object;
fixture.Inject(sut);
sut.Should().NotBeNull();
}
...当我运行第一个测试时,我得到了以下异常:
AutoFixture.ObjectCreationExceptionWithPath : AutoFixture was unable to create an instance from Moq.Mock`1[System.IO.Stream] because creation unexpectedly failed with exception. Please refer to the inner exception to investigate the root cause of the failure.
Inner exception messages:
System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)第二次测试成功。
我希望能够使用AutoFixture创建类的实例,它接受WebSocket作为构造函数参数,而不需要首先注入模拟对象(最终,这样我就可以使用AutoMoqData属性,并摆脱一些样板)。我在这里有没有什么误用或误解,或者这是一个更好的GitHub问题吗?在此期间,我可以做些什么来解决这个问题?
发布于 2018-09-17 05:31:57
您观察到这个问题是因为AutoFixture的工厂发现策略。当您尝试创建抽象类型的对象时,AutoFixture仍会检查该类型以查找用于激活该对象的静态工厂方法。在您的特定情况下,WebSocket类型包含这样的方法,因此使用了其中的一些方法。它看起来不能很好地处理自动生成的输入值,因此失败并出现异常。
您可以自定义AutoFixture,以始终模拟WebSocket类型:
fixture.Register((Mock<WebSocket> m) => m.Object);刚刚在最新版本的产品(AutoFixture 4.5.0,Moq 4.10.0)上进行了测试,它的效果非常好。
https://stackoverflow.com/questions/52175276
复制相似问题