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?
Apply a constraint to an actual value, succeeding if the constraint is satisfied and throwing an assertion exception on failure. Asserts that a condition is true. If the condition is false the method throws an AssertionException. Asserts that a condition is true.
Throws "attempts to invoke a code snippet, represented as a delegate, in order to verify that it throws a particular exception." The () => DoSomething() syntax represents a lambda, essentially an anonymous method. So in this case, we are telling Assert. Throws to execute the snippet o. Foo() .
So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert. Throws assertion will fail. However if an exception of the correct type is thrown then you can now assert on the actual exception that you've saved in the variable.
The Test attribute is one way of marking a method inside a TestFixture class as a test. It is normally used for simple (non-parameterized) tests but may also be applied to parameterized tests without causing any extra test cases to be generated. See Parameterized Tests for more info.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With