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?

Answers


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

Need Your Help

Style/Template a DataGridView For Behind-Code-Use WPF

c# .net wpf user-interface

I have to create data grids on the fly using the code behind WPF. I have to add new DataGrids on the fly to my window, but I would like them to be formated similar. I cannot get the Style to work t...

Need to know how fork works?

c process fork

I am trying the following C code:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.