简体   繁体   中英

NUnit data driven unit test with datasource

I have one data source like -4,-3,-3,-2,-1,0,1,2,2,3,4 , I have one function and this function can capture repeated number for example in this data source we have -3,2 are repeated .The repeated numbers are reported in end of the program. I couldn't find good example(I spent 3 hours). How can I implement a unit test with NUnit that can be test the same situation and it tells me the results, if you have some example , It will be very useful to me.(Really appreciated).

You can use TestCase attributes for simple data like what you've described.

[Test]
[TestCase(new[] { -4, -3, -3, -2, -1, 0, 1, 2, 2, 3, 4 }, new []{-3,2})]
public void YourTest(int[] given, int[] expected)    
{  ... }

Note: ReSharper (at least my version of it) doesn't honor multiple test cases like this one so I had to confirm multiple test cases with the NUnit GUI.

First things first - get a working test. Something like this:

    [Test]
    public void DetectsMinusThreeAndTwo()
    {
        RepeatingDigitsDetector target = new RepeatingDigitsDetector();
        int[] source = new int[] { -4, -3, -3, -2, -1, 0, 1, 2, 2, 3, 4 };
        int[] expected = new int[] { -3, -2 };
        int[] actual = target.GetRepeats(source);
        Assert.AreEqual(expected.Length, actual.Length, "checking lengths");
        for (int i = 0; i < expected.Length; i++)
        {
            Assert.AreEqual(expected[i], actual[i], "checking element {0}", i);
        }
    }

Later, you can start adding in goodies like the TestCase or TestCaseSource attributes. But if you're trying to do TDD (as the tag implies), you need to start with a test.

I would recommend TestCaseSource in this instance. Several tests could make the data harder to read inside the TestCase attribute.

As your test data gets complex, it will be difficult to handle. Consider storing your data in another source such as excel, json or Database.

I personally like storing test data in embedded json files. The package JsonSectionReader provides good support for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM