Search code examples
c#.netxunitautofixturexunit2

Can I customise a Fixture in an XUnit constructor for use with Theory and AutoData?


Here is what I am trying to do:

public class MyTests
{
    private IFixture _fixture;

    public MyTests()
    {
        _fixture = new Fixture();
        _fixture.Customize<Thing>(x => x.With(y => y.UserId, 1));
    }

    [Theory, AutoData]
    public void GetThingsByUserId_ShouldReturnThings(IEnumerable<Thing> things)
    {
        things.First().UserId.Should().Be(1);
    }
}

I would expect the IEnumerable<Thing> things parameter passed into the test to each have a UserId of 1 but this is not what happens.

How can I make this so?


Solution

  • You can do that by creating a custom AutoData attribute derived-type:

    internal class MyAutoDataAttribute : AutoDataAttribute
    {
        internal MyAutoDataAttribute()
            : base(
                new Fixture().Customize(
                    new CompositeCustomization(
                        new MyCustomization())))
        {
        }
    
        private class MyCustomization : ICustomization
        {
            public void Customize(IFixture fixture)
            {
                fixture.Customize<Thing>(x => x.With(y => y.UserId, 1));
            }
        }
    }
    

    You may also add other Customizations. Just keep in mind that the order matters.


    Then, change the test method to use MyAutoData attribute instead, as shown below:

    public class MyTests
    {
        [Theory, MyAutoData]
        public void GetThingsByUserId_ShouldReturnThings(IEnumerable<Thing> things)
        {
            things.First().UserId.Should().Be(1);
        }
    }