Search code examples
c#interfacemoqautofixtureautomoq

AutoFixture + AutoMoq: Create mock with excluded property


For example ISomething is a interface with three properties: string Name and int Count and some complex property ImComplex (with circular dependencies etc) that I don't wanna AutoFixture to build up. So I need AutoFixture to create a Mock of ISomething with Name and Count set up by its default algorithm and ImComplex as null. But if I try to solve it like this i get an exception:

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.

What should I do?


Solution

  • Build disables all customizations (as stated in the method's documentation), so it won't work together with AutoConfiguredMoqCustomization.

    If the problem is that the property has a circular dependency then you can either:

    1. reconsider your design (the reason why AutoFixture, by default, throws when it finds a circular dependency it because these are usually design smells)
    2. configure AutoFixture to allow circular dependencies, up to a certain depth

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