AutoFixture + AutoMoq:创建排除的模拟 属性

AutoFixture + AutoMoq: Create mock with excluded property

例如 ISomething 是一个具有三个属性的接口:string Nameint Count 以及一些复杂的 属性 ImComplex (具有循环依赖等)我不想建立 AutoFixture。所以我需要 AutoFixture 创建一个 ISomething 的 Mock,其中 NameCount 由其默认算法设置,ImComplex 为 null。但是如果我尝试这样解决它,我会得到一个例外:

fixture.Customize(new AutoConfiguredMoqCustomization());
var some = fixture.Build<ISomething>().Without(x=>x.ImComplex).Create<ISomething>();

Ploeh.AutoFixture.ObjectCreationException : The decorated ISpecimenBuilder could not create a specimen based on the request: RP.Core.IInformationUnit. This can happen if the request represents an interface or abstract class; if this is the case, register an ISpecimenBuilder that can create specimens based on the request. If this happens in a strongly typed Build expression, try supplying a factory using one of the IFactoryComposer methods.

我该怎么办?

Build 禁用所有自定义(如方法文档中所述),因此它不能与 AutoConfiguredMoqCustomization.

一起使用

如果问题是 属性 具有循环依赖性,那么您可以:

  1. 重新考虑您的设计(默认情况下,AutoFixture 在发现循环依赖时抛出的原因是因为这些通常是设计味道)
  2. 配置 AutoFixture 以允许循环依赖,达到一定深度

    fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList()
        .ForEach(b => fixture.Behaviors.Remove(b));
    
    int recursionDepth = 2;
    fixture.Behaviors.Add(new OmitOnRecursionBehavior(recursionDepth));