1

I am trying to use NUnit with a Generic TestCase as per this answer: NUnit TestCase with Generics from @György Kőszeg.

However, due to what I test, I need to use a where constraint with a complex type passed in (class), otherwise the compiler erros with error CS0314.

[TestCase(typeof(SomeClass))]
[TestCase(typeof(SomeOtherClass))]
public void GenericTest<T>(T instance) where T : ISomeInterface
{
    Console.WriteLine(instance);
}

SomeClass and SomeOtherClass are valid classes that implement ISomeInterface.

This does fail with the following error:

An exception was thrown while loading the test. System.ArgumentException: GenericArguments[0], 'System.RuntimeType', on '[...]GenericTestT' violates the constraint of type 'ISomeInterface'.

I can't get that to work. If I change it to nameof(SomeClass) to try it with the string value, I get the same error that String does not match the constraint.

rklec
  • 73
  • 10

1 Answers1

2

Oh dear, of course it has to interfere it from the type.

As such, it get's a little harder as TestCases need to be static, but we can use TestCaseSource.

[TestCaseSource(nameof(GetTestCases))]
public void GenericTest<T>(T instance) where T : ISomeInterface
{
    Console.WriteLine(instance);
}

private static IEnumerable<TestCaseData> GetTestCases()
{
    yield return new TestCaseData(new SomeClass());
    yield return new TestCaseData(new SomeOtherClass());
}

As an unrelated addition, you can discard the instance if you don't actually use it and just wanted to use it for the type:

[TestCaseSource(nameof(GetTestCases))]
public void GenericTest<T>(T _) where T : ISomeInterface
{
    // ...
}
rklec
  • 73
  • 10