Writing unit tests that expects a given type of exception under given circumstances is essential for any test suite. Although it is useful to use the correct assertion types when testing for exceptions. In this post I will provide some guidance on why to use Assert.Throws<>() instead of ExpectedException.
Using the ExpectedException:
Copy to Clipboard
In the above example whenever / wherever an exception of the given type is thrown inside the test, the test is considered passed.
A refactored example:
Copy to Clipboard
Now, instead of using the ExpectedException, I use Assert.Throws<>(). This provides a number of benefits / advantages:
- Readability
- The test is now more readable, the reader is not in doubt of where in the code the exception is expected to be thrown. Furthermore, the ExpectedException attribute is easily overseen, which makes it difficult to understand what the intent of the test is.
- Multiple conditions
- It is possible to test other conditions. Using the ExpectedException you cannot test anything else than the whether the exception is thrown.
- Possible false expectation
- Setting the ExpectedException on a test case, makes it open to be passed whenever an exception of the given type is thrown inside the test. This could lead to some serious and unforeseen side-effects.