Testing for exceptions with [TestCase] attribute in NUnit 3?

后端 未结 2 1722
别那么骄傲
别那么骄傲 2021-02-03 21:05

How do I test for exceptions in a TestCase with NUnit3?

Let\'s say I have a method Divide(a,b) defined as follows:

public d         


        
2条回答
  •  礼貌的吻别
    2021-02-03 21:33

    ExpectedException would have been the correct method for NUnit 2.X, but it was removed from NUnit 3.

    There's a various snippets of discussion in the NUnit Google Group and the equivalent Dev group - but it looks like the decision was made that it's generally a better design pattern to test expected outcomes, and exceptions in separate methods. (link)

    The only way to do this in NUnit 3, would be to break it down in to two separate tests. (Confirmed in a similar question answered by the NUnit core team, here.)

    [TestCase(-10, 2, -5)]
    [TestCase(-1, 2, -0.5)]
    public void TestDivide(double a, double b, double result)
    {
        Assert.That(_uut.Divide(a, b), Is.EqualTo(result));
    }
    
    [TestCase(-1, 0)]
    public void TestDivideThrows(double a, double b)
    {
        Assert.That(() => _uut.Divide(a, b), Throws.TypeOf());
    }
    

提交回复
热议问题