Customizing AutoFixture to simplify our tests setups

pedrostc

Pedro Osternack Corrêa

Posted on January 3, 2023

Customizing AutoFixture to simplify our tests setups

On a previous post I've showed how to register an implementation for an interface to be used by AutoFixture. We can simplify that a bit by adding customizations to our AutoFixture instance.

Let's say that we have the following test method:

public void TestOne()
{
    var fixture = new Fixture();

    // registering our interface implementation.
    fixture.Register<IConverter<Type1, Type2>>(() => new T1toT2Converter());

    var sut = fixture.Create<ServicyMcServiceFace>();
}
Enter fullscreen mode Exit fullscreen mode

We can an AutoFixture customization by implementing the ICustomization interface and passing said implementation to our fixture object.

Let's create a customization that will register our IConverter implementation for us so we don't need to do that on the test:

// Our customization
public class ConverterCustomization : ICustomization
{
    // the method declared by the ICustomization interface
    public void Customize(IFixture fixture)
    {
        fixture.Register<IConverter<Type1, Type2>>(() => new T1toT2Converter());
    }
}
Enter fullscreen mode Exit fullscreen mode

Now we can refactor our test method to use that customization.

public void TestOne()
{
    var fixture = new Fixture().Customize(new ConverterCustomization());

    var sut = fixture.Create<ServicyMcServiceFace>();
}
Enter fullscreen mode Exit fullscreen mode

Because of our customization every time we use that fixture instance to create an object that needs an instance of IConverter<Type1, Type2>, said object will receive an instance of T1toT2Converter, the same as before.

This pattern can be very useful for complex domains with lots of interfaces or if we want to provide some rules for the creation of our objects in a clean and easily reusable manner.

💖 💪 🙅 🚩
pedrostc
Pedro Osternack Corrêa

Posted on January 3, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related