Search code examples
c#unit-testingtestingxunitautofixture

AutoFixture and XUnit2 - Combining TheoryData and AutoData


In the tests I'm currently writing I need to mix test-specific data with random entries that ideally I would like AutoFixture to generate. I'm using TheoryData to create test-specific data set:

internal sealed class TestSpecificData : TheoryData<int, string>
{
    // Addition of test cases input.
}

In my XUnit2 test case I would like to do the following:

[Theory]
[AutoData]
[ClassData(TestSpecificData)]
public void MyTestCase(int first, string second, double third)
{
    // Test scenario.
}

In the above test case I would like AutoFixture to generate only the last parameter: "double third" and use data available in TestSpecificData theory data for the first two parameters. Attempting to run above code results in InvalidOperationException with following message:

"The test method expected 3 parameter values, but 2 parameter values were provided."

I know I could use an InlineAutoData attribute, but there are a lot of test-specific entries and it would not be an ideal solution, since I would have to declare a separate InlineAutoData for each case. Moreover I would like to reuse test entries in different test cases, so this is why I'm attempting to use TheoryData. I also tried to create a custom AutoFixture attribute that inherits from AutoDataAttribute, but I can't seem to make it work like I would like it to. I would appreciate any suggestions or different solutions that would help me achieve desired outcome.

Thank you!


Solution

  • Unfortunately there is currently no support for ClassDataAttribute in AutoFixture.XUnit2. However there is currently a pull request opened that adds this exact feature to AutoFixture.NUnit3. You could draw some inspiration from there.

    If you manage to come up with an implementation please consider filing a pull request on the official AutoFixture repository.