xUnit.net Theory where MemberData is from derived class

Viewed 4556

Using xUnit.net, it is possible for a Theory to have its MemberData originate from a derived class?

public abstract class BaseTest
{
    public abstract IEnumerable<object[]> Data();

    [Theory]
    [MemberData(nameof(Data))]
    public void TestData(string expected, string actual)
    {
        // assert goes here
    }
}

public class ComplexTest : BaseTest
{
    public override IEnumerable<object[]> Data()
    {
        // data goes here
    }
}

The code above results in the following error message:

System.NotSupportedException : Specified method is not supported.

4 Answers

Another way is to add MemberData only to derived class. It will check members by name and take the correct one from the current class. The only thing that analyzer with warn that you must specify member in base class (that by default treated as an error), so you have to disable this rule. If you try to specify this method in both classes - base and derived only base classes would be used. The issue about analyzer described in xunit github: https://github.com/xunit/xunit/issues/1243

Your example may look:

public abstract class BaseTest
{
    [Theory]
#pragma warning disable xUnit1015 // MemberData must reference an existing member
    [MemberData(nameof(Data))]
#pragma warning restore xUnit1015 // MemberData must reference an existing member
    public void TestData(string expected, string actual)
    {
        // assert goes here
    }
}

public class ComplexTest : BaseTest
{
    public static IEnumerable<object[]> Data()
    {
        return data;
        // data goes here
    }
}
Related