Search code examples
unit-testingxunit.netautofixture

Using AutoFixture to set properties on a collection as data for an Xunit theory


I'm new to Xunit and AutoFixture, and writing a theory that looks like:

[Theory, AutoData]
public void Some_Unit_Test(List<MyClass> data)
{
    // Test stuff
}

MyClass looks like:

public class MyClass
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
}

This causes AutoFixture to create a list of items with random values for each property. This is great, but I would like the IsActive property to always be true.

I could set it to true at the start of every test but I'm guessing there is a smarter way. I looked at InlineData, ClassData, PropertyData, even Inject() but nothing quite seemed to fit.

How can I improve this?


Solution

  • Here is one way to do this:

    public class Test
    {
        [Theory, TestConventions]
        public void ATestMethod(List<MyClass> data)
        {
            Assert.True(data.All(x => x.IsActive));
        }
    }
    

    The TestConventionsAttribute is defined as:

    internal class TestConventionsAttribute : AutoDataAttribute
    {
        internal TestConventionsAttribute()
            : base(new Fixture().Customize(new TestConventions()))
        {
        }
    
        private class TestConventions : ICustomization
        {
            public void Customize(IFixture fixture)
            {
                fixture.Customize<MyClass>(c => c.With(x => x.IsActive, true));
            }
        }
    }