logo

Combining Data Theories in AutoFixture.Xunit extension

xUnit.net supports parameterized tests via data theories:

public class ParameterizedTests
{
    public bool IsOddNumber(int number)
    {
        return number % 2 != 0;
    }

    [Theory]
    [InlineData(5, 1, 3, 9)]
    [InlineData(7, 1, 5, 3)]
    public void AllNumbers_AreOdd_WithInlineData(int a, int b, int c, int d)
    {
        Assert.True(IsOddNumber(a));
        Assert.True(IsOddNumber(b));
        Assert.True(IsOddNumber(c));
        Assert.True(IsOddNumber(d));
    }
}

The above example can be found in Hamid Mosalla’s post xUnit Theory: Working With InlineData, MemberData, ClassData.

As you can see in that post, some popular attributes are:

AutoFixture.Xunit extension includes a very useful type, for providing auto-data theories, called AutoMoqDataAttribute.

Context

Imagine a scenario where we have a test method with 3 parameters:

[Theory]
[InlineAutoData("foo")]
[InlineAutoData("foo", "bar")]
public void Test(string s1, string s2, MyClass myClass)
{
    // ...
}

We want the first parameters to be supplied by InlineDataAttribute and the rest by AutoFixture using AutoMoqDataAttribute.

This is possible using the InlineAutoDataAttribute type which is now on the trunk and will be available on next public release (after AutoFixture version 2.1).

How it works

InlineAutoDataAttribute provides a data source for a data theory, with the data coming from inline values combined with auto-generated data generated by AutoFixture.

InlineAutoDataAttribute derives from CompositeDataAttribute, an implementation of DataAttribute that composes other DataAttributes.

The implementation turns out to be a bit tricky:

While this feature comes with AutoFixture.Xunit extension, the CompositeDataAttribute class depends only on the xunit.extensions assembly.