Reputation: 151
I am using NUnit with the TestCaseSource
attribute to do data-driven testing with dynamic data in the same approach as NUnit TestCaseSource pass value to factory and
How can I pass dynamic objects into an NUnit TestCase function?
In each case they use IEnumerable<TestCaseData>
to specify data. It appears from the NUnit documentation here http://nunit.org/index.php?p=testCaseSource&r=2.5 that this needs to be a static or instance member of the same class as the TestCase
.
I would like to refactor this into another class since I want to use the same TestCaseSource
attribute. Does anyone know if this is possible?
Upvotes: 15
Views: 4839
Reputation: 7947
You can do something like:
[TestCaseSource(typeof(CommonSource), "GetData")]
public void MyTest(...) {...}
The first argument to the attribute constructor tells it which class to look in and the second argument tell it the specific member name to use.
Upvotes: 12
Reputation: 371
Robert already answered it, but I will try to improve his answer with the new features of C#.
public static class TestCasesData
{
private static string[] TestStringsData()
{
return new string[] {"TEST1", "TEST2"};
}
private static string[] TestIntsData()
{
return new in[] { 1, 2};
}
}
[TestFixture]
public class MyTest
{
[Test]
[TestCaseSource(typeof(TestCasesData ), nameof(TestCasesData .TestStringsData))]
public void TestCase1(...)
{
}
[Test]
public void TestCase2(
[ValueSource(typeof(TestCasesData), "TestIntsData")] int testData,
)
{
}
}
Upvotes: 24
Reputation: 12328
If NUnit requires the TestCaseSource to be in the same class as the tests, the easiest way might be to have that method call your common method. Then, the details can be kept elsewhere, so you minimize duplicate code.
For example, each test class might have the following:
IEnumerable LocalSource()
{
return CommonSource.GetData();
}
The CommonSource class would be a separate class that loads the data necessary for the tests.
Upvotes: 3