Reputation: 629
I am wondering if there is a way to use TestCaseSource
in a base test class with data given from the derived class in a generic way.
For example, if I had the following base class:
public abstract class Base<T>
{
protected static T[] Values;
[TestCaseSource(nameof(Values))]
public void MyTest(T[] values)
{
// Some test here with the values;
}
}
And the following derived class
[TestFixture]
public class Derived : Base<string>
{
[OneTimeSetup]
public void OneTimeSetup()
{
Values = new[] { "One", "Two" };
}
[TestCaseSource(nameof(Values))
public void DerivedSpecificTest(T[] values)
{
// Some test here with the values;
}
}
I assume what I am doing is incorrect, because, when I run the derived class tests, I get this exception on both tests: Failed: System.Exception: The test case source could not be found.
However, the example should get across what I am trying to do (if what I am trying to is possible). Essentially I am wondering if it is possible to use TestCaseSource
in the base class with data given from the derived class.
Any help is appreciated, and I can answer questions if clarity is needed.
I should also mention that if I initialize Values
to an empty, zero length array, the tests return as inconclusive. I assume this is because the data changes while the tests are being created (some behavior with NUnit?).
And I can get the tests to run if I don't use TestCaseSource
, but instead just mark the tests with the attribute Test
, and insert my test logic into a loop with each array value. This is not ideal as when a test fails, it is difficult to see exactly which input caused it to fail, because, each input is not separated out.
Upvotes: 2
Views: 1271
Reputation: 739
This should get you started, no doubt there is a more elegant solution.
using System;
using NUnit.Framework;
namespace UnitTestProject1
{
public class Base<T>
{
private static T[] Values;
[TestCaseSource(nameof(Values))]
public void MyTest(T value)
{
Console.WriteLine($"Base: {value}");
// Some test here with the values;
}
}
[TestFixture]
public class Derived : Base<string>
{
private static string[] Values= new[] { "One", "Two" };
[TestCaseSource(nameof(Values))]
public void DerivedSpecificTest(string value)
{
// Some test here with the values;
Console.WriteLine($"Derived: {value}");
}
}
}
Upvotes: 3