AutoFixture / AutoMoq:无法创建实例(`BadImageFormatException`)

问题描述 投票:1回答:1

以下是我目前遇到的问题的最小示例:

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问题?在此期间,我可以做些什么来解决这个问题?

moq autofixture automoq
1个回答
2
投票

由于AutoFixture的工厂发现策略,您会发现此问题。当您尝试创建抽象类型的对象时,AutoFixture仍会检查该类型以查找用于激活该对象的静态工厂方法。在您的特定情况下,WebSocket类型包含此类方法,因此使用其中一些方法。看起来它对自动生成的输入值不起作用,因此失败并出现异常。

您可以自定义AutoFixture,以始终模拟WebSocket类型:

fixture.Register((Mock<WebSocket> m) => m.Object);

刚刚测试了最新版本的产品(AutoFixture 4.5.0Moq 4.10.0),它就像一个魅力。

© www.soinside.com 2019 - 2024. All rights reserved.