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);
}
I had occasion to do something similar today, and wasn't happy with using reflection.
I decided to leverage [TestCaseSource] instead by delegating the test logic as a test context to a generic testing class, pinned on a non-generic interface, and called the interface from individual tests (my real tests have many more methods in the interface, and use AutoFixture to set up the context):
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:
You can make custom GenericTestCaseAttribute
Here is implementation of GenericTestCaseAttribute
I slightly modified the TestCaseGenericAttribute somebody posted here:
This version expects one list of all parameters, starting with the type parameters, starting with the type paramters. Usage:
Start with the test first--even when testing. What do you want to do? Probably something like this:
Then you can just make your test a plain old function test. No [Test] marker.
I did something similar last week. Here's what I ended up with:
And then the test itself: