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.
Currently with plain JUnit you have to use try-catch if you want to verify something after the assertion is thrown. With JUnit 4.13 (not released yet) you can use
expectThrows(Exception.class, () -> callTheMethod());
new Verifications() { {
statusMessage.send("Failure", <expected data>);
} }
As an alternative you can use the Fishbowl's ignoreException.
ignoreException(() -> callTheMethod());
new Verifications() { {
statusMessage.send("Failure", <expected data>);
} }
Full disclosure: I'm the author of Fishbowl.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With