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
You can simply include
Type
as an input parameter instead. E.g.:There is no need to go with generics on xunit.
Edit (if you really need generics)
1) You need to subclass
ITestMethod
to persist generic method info, it also has to implementIXunitSerializable
2) You need to write your own discoverer for generic methods, it has to be subclass of
IXunitTestCaseDiscoverer
3) Finally you can make your attribute for generic methods and hook it to your custom discoverer by
XunitTestCaseDiscoverer
attributeUsage: