Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFixture Register type globally

Tags:

c#

autofixture

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?

like image 535
Mark Walsh Avatar asked Sep 08 '15 09:09

Mark Walsh


3 Answers

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

}
like image 158
dcastro Avatar answered Oct 19 '22 19:10

dcastro


I created a convention class as suggested by @drcastro but I ended up creating a TestBase class which I inherit from in my Unit test class

  public class TestBase
    {
        public IFixture GenerateNewFixture()
        {
            return new Fixture().Customize(new AutoFixtureConventions());
        }
    }

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

        }

        private class MongoObjectIdCustomization : ICustomization
        {
            public void Customize(IFixture fixture)
            {
                fixture.Register(ObjectId.GenerateNewId);
            }
        }
    }
like image 2
Mark Walsh Avatar answered Oct 19 '22 18:10

Mark Walsh


You could also do something like this

    public class FixtureWithFoo: Fixture
    {
        public FixtureWithFoo()
        {
            Customizations.Add(new FooCustomization()); 
            //Or register something else
        }
    }

and then use it in your test

var fixture = new FixtureWithFoo();
like image 1
Sateesh Pagolu Avatar answered Oct 19 '22 19:10

Sateesh Pagolu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!