Contents
When do you need to catch the expected exception?
If you need to catch the expected exception (i.e., to assert certain details, like the message / properties on the exception), it’s important to catch the specific expected type, and not the base Exception class.
Which is a better way to deal with unexpected exceptions?
So to answer your question, a better way to deal with unexpected Exception is to find them by enhancing your test-case it fix it. The idea to UNIT test a method is to make sure it is a reliable method. Reliability means that for a given input, output is always the expected one.
How to test an assert failure as an exception?
Many unit testing frameworks implement assertion failures as exceptions. So the Assert.Fail() in the second case will get caught by the catch(Exception) block, which will hide the exception message.
How to test that an exception does not throw?
AssertDoesNotThrowException () takes the same delegate and asserts that it does not throw an exception. This pairing can be very useful when you want to test that an exception is thrown in one case, but not the other.
Which is the best way to test exceptions?
With most .net unit testing frameworks you can put an [ExpectedException] attribute on the test method. However this can’t tell you that the exception happened at the point you expected it to. That’s where xunit.net can help.
How to test exceptions with Assert and catch?
As an aside, when debugging unit tests which throw exceptions, you may want to prevent VS from breaking on the exception. Just to give an example of Matthew’s comment below, the return of the generic Assert.Throws and Assert.Catch is the exception with the type of the exception, which you can then examine for further inspection:
What’s the best way to test exceptions in NUnit?
As of v 2.5, NUnit has the following method-level Assert s for testing exceptions: Assert.Throws, which will test for an exact exception type: And Assert.Catch, which will test for an exception of a given type, or an exception type derived from this type: