3 Answers
3

Don't catch exceptions in unit tests. You are unit testing to find errors and situations where exceptions are raised.

The unit test framework should handle exceptions in a sane manner. Most (if not all) xUnit frameworks have a construct to expect certain exceptions which you use when you want to induce a particular exception condition in the system under test and have a test pass if the expected exception is raised but fail if it does not.

I think advanced testing framework can handle exception very well, even I find that in Visual studio we can test against exceptions like you said "expected exception". So its good to know and sharing. Thanks..
–
VikasAug 18 '11 at 8:43

Sometimetime, you want to check if an Exception is thrown, because good testing don't test only cases were things works, but also cases when they fail.
–
deadalnixAug 18 '11 at 9:05

You DO want to catch exceptions, as you DO want to test the situations in which exceptions happen (especially your own exceptions). If you write code that's designed to fail with an exception under certain conditions, those conditions should be a part of your test suite, and thus should be tested. Under those tests, those exceptions should be caught and analysed.
–
jwentingSep 7 '11 at 11:04

@Jwenting Read the second paragraph - Unit testing frameworks catch the exceptions and allow tests to pass if certain exceptions are raised and fail if they are not
–
mcottleSep 7 '11 at 15:33

When you say that you expect a test to raise a particular exception, you will know when ANY line in that test raises that particular exception.

That's not quite the same thing as knowing that the method under test throws the exception.

If your test involves setting up an object or context (within the test, not within your framework's version of SetUp), you might be better off wrapping the single line you actually want to test in a try/catch, possibly with a helper.

Good example! I try to be very careful about limiting the "test" phase to just the precise test, but I'll remember this trick for when I just can't figure out a way to pull that off (e.g., when testing for a race condition and need 'setup' close to the 'test' to hit the condition).
–
Ethel EvansAug 24 '11 at 18:14

In general, you should just let the exception out, and the testing framework will give you a nice report with all the information you need.

But in the TDD methodology, we are expected to follow that steps:

Write a test

Watch it fail, and make the error understandable

Correct the code

Refactor the code and the test

When you let an exception out, if the error is clear, then it is fine.
But sometimes the exception is obscure, or even misguiding.
How could you let that be in your code (for you later when you will have forgotten, or for a team member that will loose big time figuring out the problem) ? So my policy is: "If it is necessary to make a failure clear, you need to catch the exception".