JUnit, exceptions in @Before and @After methods

JUnit spec (not very easy to find) states, that if there's an exception in the @Before method, the test is not called. True. BUT

JUnit spec does not state that in this case the @After method is called.

spec also does not state that if there's an exception in both the
@Before and @After methods, the second exception (guess which one)
overrides the first one. In my case the first one causes the second one
(the first one is ConnectionClosed or similar, the second one is a
NullPointerException because the resource is not initialized).

So the
real reason for the problem is lost. One will say - avoid exceptions in
the @After method - that's what I just did (and the real exception was
printed), but finding the reason for that was not easy and

I'm using junit 4.4, the default runner is JUnit4ClassRunner, JUnit4ClassRunner is calling ClassRoadie.runProtected():

public void runProtected() {
    try {
    } catch (FailedBefore e) {
    } finally {

This is the reason for the mentioned override. I hate when finally does that.

Leave a Reply

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed.