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?
I prefer assert.throws since it allows me to verify and assert other conditions after the exception is thrown.
The first allows you to test for more than one exception, with multiple calls:
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 specifyexact
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 thanExpectedException()
attribute.If you are using older version(<=2.0) of
NUnit
then you need to useExpectedException
.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
You may also strong type the error you're expecting (like the old attrib version).