Using AutoFixture to Set Collection Properties as Data for Xunit Theory
I am new to Xunit and AutoFixture and am writing a theory that looks like this:
[Theory, AutoData]
public void Some_Unit_Test(List<MyClass> data)
{
// Test stuff
}
MyClass looks like this:
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
This causes AutoFixture to generate a list of items with random values ββfor each property. This is great, but I would like the property to IsActive
always be true.
I could set it to true at the beginning of each test, but I guess there is a smarter way. I looked at InlineData
, ClassData
, PropertyData
, even Inject()
, but nothing like did not fit.
How can I improve this?
source to share
Here's one way to do it:
public class Test
{
[Theory, TestConventions]
public void ATestMethod(List<MyClass> data)
{
Assert.True(data.All(x => x.IsActive));
}
}
TestConventionsAttribute
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));
}
}
}
source to share