I'm really a newbie to JUnit and unit testing in general and I'm struggling to find the right approach. What is the better way to deal with unexpected exceptions, and why?
Method A:
- first catch the expected ones, fail the test with a message
- in the last catch block, catch a general Exception and fail the test with some "Unexpected exception has occured" message
Method B:
- catch only the expected ones, fail with a message
- mark the test method with
throws Exception
and let anything unexpected "bubble up" completely out of the test
And to add to the confusion, by saying "unexpected exception", I mean either one of these things:
- an exception that the method being tested claims to throw, but on in this case. For example, my method throws IllegalArgumentException and NullPointerException, but in this try block, I expect it to throw IllegalArgument; NullPointer is considered unexpected. Catch and fail or bubble up?
- a general Exception I really cannot anticipate
I'm aware this question comes out a bit confusing, I'm getting lost in it myself, but hopefully someone will give me any kind of hint. Won't blame you for downvotes, it's still worth the risk :)