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

后端 未结 2 1717
别那么骄傲
别那么骄傲 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:20

    I agree with the Corpus Gigantus's answer but why don't you simplify thing like this:

    [TestCase(-10, 2, -5)]
    [TestCase(-1, 2, -0.5)]
    [TestCase(-1, 0, null, typeof(ArgumentException))]
    public void TestDivide(double a, double b, double result, Type exception = null)
    {
        if(exception != null)
        {
            Assert.Throws(exception, delegate { _uut.Divide(a, b);  });
                    
        } else Assert.That(_uut.Divide(a, b), Is.EqualTo(result));
    }
    

    In this way, the expected exception is part of the test parameters as well, note that you can only have two outcome, either the division succeeds or throws.

提交回复
热议问题