xUnit theory test using generics

asked9 years ago
last updated8 years ago
viewed15.7k times
Up Vote28Down Vote

In xUnit I can have a Theory test that uses generics in this form:

[Theory]
[MemberData(SomeScenario)]
public void TestMethod<T>(T myType)
{
    Assert.Equal(typeof(double), typeof(T));
}

public static IEnumerable<object[]> SomeScenario()
{
    yield return new object[] { 1.23D };
}

Which will give me the generic T parameter as double. Is it possible to use MemberData to specify the generic type parameter for a test with a signature like:

[Theory]
[MemberData(SomeTypeScenario)]
public void TestMethod<T>()
{
    Assert.Equal(typeof(double), typeof(T));
}

If it is not possible with MemberData or any other provided attribute (which I'm suspecting that it isn't), is it possible to create an attribute for Xunit that can achieve this? Maybe something along the lines of specifying Types in the Scenarios method and using reflection in a similar manner to Jon Skeet's answer here: Generics in C#, using type of a variable as parameter