简体   繁体   English

TDD nUnit用于一种方法的多个断言

[英]TDD nUnit multiple asserts for one method

Using TDD first time in my life today. 在我今天的生活中第一次使用TDD。 I am using nUnit. 我正在使用nUnit。

I have one method, where I can insert multiple different inputs and check if result works. 我有一个方法,我可以插入多个不同的输入,并检查结果是否有效。

I read that multiple asserts in one test is not a problem, and I really don't want to write new test for each input. 我读到一次测试中的多个断言不是问题,我真的不想为每个输入编写新的测试。

Example with multiple asserts: 多个断言的示例:

    [TestFixture]
public class TestClass
{

    public Program test;

    [SetUp]
    public void Init()
    {
        test = new Program();

    }
    [Test]
    public void Parse_SimpleValues_Calculated()
    {
        Assert.AreEqual(25, test.ParseCalculationString("5*5"));
        Assert.AreEqual(125, test.ParseCalculationString("5*5*5"));
        Assert.AreEqual(10, test.ParseCalculationString("5+5"));
        Assert.AreEqual(15, test.ParseCalculationString("5+5+5"));
        Assert.AreEqual(50, test.ParseCalculationString("5*5+5*5"));
        Assert.AreEqual(3, test.ParseCalculationString("5-1*2"));
        Assert.AreEqual(7, test.ParseCalculationString("7+1-1"));
    }
}

But when something fails it is very hard to read which assert failed, I mean if you have them a lot, you have to go through all and find the right assert. 但是当一些东西失败时,很难读出哪个断言失败了,我的意思是如果你有很多断言,你必须通过所有断言找到正确的断言。

Is there any elegant way to show what input did we set if assert fails, instead of result and expected result? 是否有任何优雅的方式来显示我们在断言失败时设置了什么输入,而不是结果和预期结果?

Thank you. 谢谢。

I mean if you have them a lot, so you have to go through all. 我的意思是,如果你有很多,所以你必须经历所有。

No you don't - you just look at the stack trace. 不,你不 - 你只看堆栈跟踪。 If you're running the tests within an IDE, I find that that's easily good enough to work out which line failed. 如果您在IDE中运行测试,我发现这很容易就可以确定哪条线路出现故障。

That said, there is a (significantly) better way - parameterized tests with TestCaseAttribute . 这就是说, 一个(显著)更好的方式-与参数测试TestCaseAttribute So for example: 例如:

[Test]
[TestCase("5*5", 25)]
[TestCase("5*5*5", 125)]
[TestCase("5+5", 10)]
// etc
public void Parse_SimpleValues_Calculated(string input, int expectedOutput)
{
    Assert.AreEqual(expectedOutput, test.ParseCalculationString(input));
}

Now your unit test runner will show you each test case separately, and you'll be able to see which one fails. 现在,您的单元测试运行器将分别向您显示每个测试用例,您将能够看到哪个失败。 Additionally, it will run all of the tests, even if an early one fails - so you don't end up fixing one only to find that the next one failed unexpectedly. 此外,它将运行所有测试,即使早期测试失败 - 因此您不会最终修复一个测试,只是发现下一个测试意外失败。

There's also TestCaseSourceAttribute for cases where you want to specify a collection of inputs separately - eg to use across multiple tests. 对于要分别指定输入集合的情况,还有TestCaseSourceAttribute ,例如,用于多个测试。

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

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