AutoFixture AutoMoq 将模拟对象转换为接口

AutoFixture AutoMoq Cast a mocked object as an interface

希望有人能给我出出主意

我需要创建一个满足以下条件的模拟对象:

  1. 它实现了 IEntity 接口。
  2. 它使用我在 EntityBase 中已有的基础实现。
  3. 这些属性是使用 AutoFixture 自动生成的。

我尝试了几种替代方法,并以以下代码结束:

fixture.Customize(new AutoConfiguredMoqCustomization());

fixture.Customize<IEntity>(c => c.FromFactory(
     () => fixture.Create<Mock<EntityBase>>().As<IEntity>().Object));

但是,我得到以下异常:

Mock 类型已经通过访问其对象进行了初始化 属性。添加接口必须在此之前完成。 :(

您可以使用 TypeRelay 告诉 AutoFixture 应该通过创建 EntityBase:

的实例来满足对 IEntity 的请求
fixture.Customizations.Insert(0, new TypeRelay(typeof(IEntity), typeof(EntityBase)));

现在,每次 AutoFixture 必须创建一个 IEntity 的实例时,它会创建一个 EntityBase 的实例,而由于 [=16],它将由 Moq 处理=].

中继非常方便,有 a few of them built-in. In fact, they enable the whole auto-mocking functionality by relaying 接口请求和抽象 类 模拟库。