简体   繁体   English

NUnit数据驱动的带有数据源的单元测试

[英]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. 我有一个数据源,如-4,-3,-3,-2,-1,0,1,2,2,3,4,我有一个函数,这个函数可以捕获重复的数字,例如在这个数据源中我们有-3,2重复。重复的数字在程序结束时报告。 I couldn't find good example(I spent 3 hours). 我找不到好的例子(我花了3个小时)。 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). 如何使用NUnit实现单元测试,可以测试相同的情况并告诉我结果,如果你有一些例子,它对我非常有用。(真的很感激)。

You can use TestCase attributes for simple data like what you've described. 您可以将TestCase属性用于简单数据,就像您所描述的那样。

[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. 注意:ReSharper(至少我的版本)不支持像这样的多个测试用例,因此我必须使用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. 稍后,您可以开始添加类似TestCaseTestCaseSource属性的内容。 But if you're trying to do TDD (as the tag implies), you need to start with a test. 但是,如果你正在试图做TDD(作为标签暗示),你需要开始与测试

I would recommend TestCaseSource in this instance. 我会在这个例子中推荐TestCaseSource Several tests could make the data harder to read inside the TestCase attribute. 一些测试可能会使TestCase属性内的数据更难读取。

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. 考虑将数据存储在另一个源中,例如excel,json或Database。

I personally like storing test data in embedded json files. 我个人喜欢将测试数据存储在嵌入式json文件中。 The package JsonSectionReader provides good support for this. JsonSectionReader为此提供了很好的支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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