AutoFixture Register type globally

There isn't a way to do this globally (or statically).

What I usually do is create a TestConventions class that contains all the customizations I want to apply to every test.

internal class TestConventions : CompositeCustomization
{
    public TestConventions() :
        base(
            new MongoObjectIdCustomization())
    {

    }

    private class MongoObjectIdCustomization : ICustomization
    {
        public void Customize(IFixture fixture)
        {
            fixture.Register(ObjectId.GenerateNewId);
        }
    }
}

And then I apply these conventions to every test:

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

If you're using the AutoFixture.XUnit2 (or AutoFixture.NUnit) plugin, you can reduce this boilerplate by defining an attribute that imports your test conventions:

public class MyProjectAutoDataAttribute : AutoDataAttribute
{
    public MyProjectAutoDataAttribute() : base(
        new Fixture().Customize(new TestConventions()))
    {

    }
}

And then apply it to your test cases:

[Theory, MyProjectAutoData]
public void SomeFact(SomeClass sut)
{

}

Tags:

C#

Autofixture