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));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With