简体   繁体   中英

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?

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));
        }
    }
}

Thank you, Nikos. This is very useful. Just a small update, now after a while and couple of versions after there is a small change with regards to the base constructor which should be called, the one above is now obsolete. It should look something like this:

    private static readonly Func<IFixture> fixtureFactory = () =>
    {
        return new Fixture().Customize(new TestConventions());
    };

    public TestConventionsAttribute()
        : base(fixtureFactory)
    {
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM