2

Is there any hook in Junit5 that reacts to fails in @Before* methods?

I use a @BeforeAll method to init environment for my tests. But this initialization may sometimes fail. I want to dump the environment, to find out whats wrong, but I need to do it before @After* methods are called, which will clear the environment and destroy all info.

We're talking about dozens of these @BeforeAll methods across the test suite, so doing it manually inside each method is not an option.

I've already tried these, but no luck:

  • TestWatcher does not work for this, since it only fires if an actual test is executed.
  • TestExecutionListener.executionFinished looks promising, but it fires after all the @After methods, which is too late for me.
  • I even tried to do it inside the @AfterAll cleanup methods, before the actual cleanup. But found no way to detect which tests were executed or if anything failed.

Any ideas?

0

1 Answer 1

2

I assume by "fails in @Before* methods" you mean exceptions? If that is the case, you could leverage the extension model as follows:

@ExtendWith(DumpEnvOnFailureExtension.class)
class SomeTest {

    static class DumpEnvOnFailureExtension implements LifecycleMethodExecutionExceptionHandler {

        @Override
        public void handleBeforeAllMethodExecutionException(final ExtensionContext context, final Throwable ex)
                throws Throwable {
            System.out.println("handleBeforeAllMethodExecutionException()");
            // dump env
            throw ex;
        }

    }

    @BeforeAll
    static void setUpOnce() {
        System.out.println("setUpOnce()");
        throw new RuntimeException();
    }

    @Test
    void test() throws Exception {
        // some test
    }

    @AfterAll
    static void tearDownOnce() {
        System.out.println("tearDownOnce()");
    }

}

The log will be:

setUpOnce()
handleBeforeAllMethodExecutionException()
tearDownOnce()

That is, the extension is notified if the @BeforeAll method fails with an exception. (Note that this is just an MWE, for the actual implementation you would extract DumpEnvOnFailureExtension and use it wherever needed.)

For further information, check out section "Exception Handling" in the user guide.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes by fails I mean Exception is thrown. Thanks, this seems to solve my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.