Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit testcasesource with data refactored into another class

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 to 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?

like image 944
james singen smythe Avatar asked Jun 07 '11 06:06

james singen smythe


2 Answers

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,
    )
    {
    }
}
like image 137
LK- Avatar answered Nov 07 '22 11:11

LK-


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.

like image 10
Robert Gowland Avatar answered Nov 07 '22 12:11

Robert Gowland