Search code examples
c#unit-testingmockingmoqautofixture

How to use IFixture.Build<T>() with AutoMoqCustomization when T is an interface?


I have an interface with some read-only properties:

interface IItem
{
    string Name { get; }
    // ... more properties
}

With Fixture.Create() method I can create a single mocked interface instance using the AutoMoqCustomization like so:

var fixture = new Fixture();
fixture.Customize(new AutoMoqCustomization());

var mockedItem = fixture.Create<IItem>();

But to create a list of those interface instances with Fixture.Build().CreateMany(), I cannot do it just by doing the following:

var mockedItems = fixture
    .Build<IItem>()
    .With(x => x.Name, "Abc")
    .CreateMany();

The reason that I need Build() is that I want to have a certain return value for a certain property, and leave the rest of the properties to be still auto-generated. But unfortunately, according to the documentation, when using Build() all the customizations on the Fixture is bypassed.

I am using the following versions: AutoFixture 4.8.0, AutoFixture.AutoMoq 4.8.0 and Moq 4.9.0.

Is there a simple way to achieve this without having to define my own ISpecimenBuilder?


Solution

  • The mock can be extracted from the object and configured

    var mockedItems = fixture.CreateMany<IItem>(3);
    
    foreach (var item in mockedItems) {
        Mock<IItem> mock = Mock.Get(item);
        mock.Setup(_ => _.Name).Returns("Abc");
    }