Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
Holf Avatar asked Oct 30 '25 17:10

Holf


1 Answers

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);
    }
}
like image 178
Nikos Baxevanis Avatar answered Nov 01 '25 07:11

Nikos Baxevanis



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!