Search code examples
c#autofixture

AutoFixture Register type globally


I am using AutoFixture in this instance to materialize objects containing a Mongo ObjectId, like so

Fixture fixture = new Fixture();
fixture.Register(ObjectId.GenerateNewId);

But I am doing this for every test. Is it possible to register this globall somehow for all tests?


Solution

  • 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)
    {
    
    }