【问题标题】:AutoFixture AutoMoq Cast a mocked object as an interfaceAutoFixture AutoMoq 将模拟对象转换为接口
【发布时间】:2017-04-20 20:43:28
【问题描述】:

希望有人能给我一些想法。

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

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

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

fixture.Customize(new AutoConfiguredMoqCustomization());

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

但是,我得到以下异常:

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

【问题讨论】:

    标签: c# unit-testing autofixture automoq


    【解决方案1】:

    您可以使用 TypeRelay 告诉 AutoFixture 应该通过创建 EntityBase 的实例来满足对 IEntity 的请求:

    fixture.Customizations.Insert(0, new TypeRelay(typeof(IEntity), typeof(EntityBase)));
    

    现在,每次 AutoFixture 必须创建 IEntity 的实例时,它都会创建 EntityBase 的实例,而这又将由 Moq 处理,这要归功于 AutoConfiguredMoqCustomization

    继电器非常方便,并且内置了a few of them。事实上,它们通过relaying 向模拟库请求接口和抽象类来启用整个自动模拟功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多