DEV Community

Pedro Osternack Corrêa
Pedro Osternack Corrêa

Posted on

1

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
thomasfe profile image
thomas

Very good series on AutoFixture, I found a blog with a bit more information on how AutoFixutre works in .net

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️