Recently, in a code review, a colleague said "Tests should not have try-catch blocks". He also pointed me to information about ExpectedException
, and I was able to use it to rewrite some of my tests that were performing checks on the exception data.
However, I'm encountering a situation where I'm not sure I can eliminate the try-catch. I'm writing a unit test for a method that will throw an exception and that will perform some behavior that I need to verify using JMockit. Suppose the code under test contains something like
try {
...code...
} catch (SomeException e) {
statusMessage.send("Failure", <parameters with some data>);
throw e;
}
The JUnit test currently looks like
@Test
public void test() {
... set things up ...
try {
callTheMethod();
fail("No exception thrown");
} catch (Exception e) {
assertEquals(SomeException.class, e.getClass());
}
new Verifications() { {
statusMessage.send("Failure", <expected data>);
} }
}
I can't find a good way to get rid of the try-catch. I don't see a problem with having it there, personally, but if I don't at least try to get rid of it I'm likely to catch heck from my colleague :) :) :)
The fail
and assertEquals
aren't necessary. If there's a simple way to tell JUnit/JMockit to simply ignore any exception from callTheMethod()
and continue, that would be fine--I can create another test to check the exception.
Is there some JUnit or JMockit feature that would let me accomplish what I'm trying to do?
[Note: Edited to make it clear that the behavior I'm testing is a call on a mocked object, not a static method call. It really isn't relevant to the question.]
Your colleague may be right in the general sense, using try-catch
to test your exception handling is less desirable than using the provided ExpectedException
utilities. However, I don't think that rule applies to your case; catching the exception so you can verify other things is perfectly reasonable. There's no other way to stop an exception from from propagating, AFAIK.