Use NUnit Assert.Throws method or ExpectedException attribute?

SamuelDavis picture SamuelDavis · Feb 22, 2013 · Viewed 67.9k times · Source

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?

Answer

Alexander Stepaniuk picture Alexander Stepaniuk · Feb 23, 2013

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.