Use NUnit Assert.Throws method or ExpectedException attribute?

允我心安 提交于 2019-11-27 17:33:10

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.

Alexander Stepaniuk

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.

Mike Parkhill

I prefer assert.throws since it allows me to verify and assert other conditions after the exception is thrown.

    [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");

    }

You may also strong type the error you're expecting (like the old attrib version).

Assert.Throws<System.InvalidOperationException>(() => breakingAction())
Gireesh k

If you are using older version(<=2.0) of NUnit then you need to use ExpectedException.

If you are using 2.5 or later version then you can use Assert.Throw()

https://github.com/nunit/docs/wiki/Breaking-Changes

How to use: https://www.nunit.org/index.php?p=exceptionAsserts&r=2.5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!