Is there any way to pass generic types using a TestCase to a test in NUnit?
This is what I would like to do but the syntax is not correct…
[Test]
[TestCase<IMyInterface, MyConcreteClass>]
public void MyMethod_GenericCall_MakesGenericCall<TInterface, TConcreteClass>()
{
// Arrange
// Act
var response = MyClassUnderTest.MyMethod<TInterface>();
// Assert
Assert.IsInstanceOf<TConcreteClass>(response);
}
Or if not, what is the best way to achieve the same functionality (obviously I'll have multiple TestCases in the real code)?
Update with another example…
Here is another example with a single generic type passed…
[Test]
[TestCase<MyClass>("Some response")]
public void MyMethod_GenericCall_MakesGenericCall<T>(string expectedResponse)
{
// Arrange
// Act
var response = MyClassUnderTest.MyMethod<T>();
// Assert
Assert.AreEqual(expectedResponse, response);
}
Best Answer
NUnit test methods actually can be generic as long as the generic type arguments can be inferred from parameters:
If the generic arguments cannot be inferred, the test runner will not have a clue how to resolve type arguments:
But in this case you can implement a custom attribute:
Usage:
And a similar customization for
TestCaseSourceAttribute
:Usage: