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?
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)
{
}
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);
}
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With