Use NUnit Assert.Throws method or ExpectedException attribute?

I have discovered that these seem to be the two main ways of testing for exceptions:

Assert.Throws<Exception>(()=>MethodThatThrows());

[ExpectedException(typeof(Exception))]

Which of these would be best? Does one offer advantages over the other? Or is it simply a matter of personal preference?


The first allows you to test for more than one exception, with multiple calls:

Assert.Throws(()=>MethodThatThrows());
Assert.Throws(()=>Method2ThatThrows());

The second only allows you to test for one exception per test function.


The main difference is:

ExpectedException() attribute makes test passed if exception occurs in any place in the test method.
The usage of Assert.Throws() allows to specify exact place of the code where exception is expected.

NUnit 3.0 drops official support for ExpectedException altogether.

So, I definitely prefer to use Assert.Throws() method rather than ExpectedException() attribute.


我更喜欢assert.throws,因为它允许我在抛出异常之后验证并断言其他条件。

    [Test]
    [Category("Slow")]
    public void IsValidLogFileName_nullFileName_ThrowsExcpetion()
    {
        // the exception we expect thrown from the IsValidFileName method
        var ex = Assert.Throws<ArgumentNullException>(() => a.IsValidLogFileName(""));

        // now we can test the exception itself
        Assert.That(ex.Message == "Blah");

    }
链接地址: http://www.djcxy.com/p/73384.html

上一篇: ExpectedException特性用法

下一篇: 使用NUnit Assert.Throws方法或ExpectedException属性?