开发者

NUnit testcasesource with data refactored into another class

I am using NUnit with the TestCaseSource attribute to do data-driven testi开发者_开发技巧ng 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?


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,
    )
    {
    }
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜