1

I'm writing a little extension that tells me in my log when a test starts, so i know which logs are related to which tests:

public class LoggingExtension implements Extension, BeforeEachCallback, AfterTestExecutionCallback {

  protected final Logger log = LoggerFactory.getLogger(getClass());

  @Override
  public void beforeEach(final ExtensionContext context) throws Exception {
    log.info("-- Test @before: {}::{} ----------------------------------------",
             context.getDisplayName(),
             context.getTestClass().map(x -> x.getSimpleName()).orElse("no test class available"));

  }

  /**
   * (non-Javadoc) ${see_to_overridden}
   */
  @Override
  public void afterTestExecution(final ExtensionContext context) throws Exception {
    context.getExecutionException()
           .ifPresent(ex -> {
             log.error("-- Test @after: {}::{} ----------------------------------------",
                       context.getDisplayName(),
                       context.getTestClass().map(x -> x.getSimpleName()).orElse("no test class available"),
                       ex);
             //             log.error("", ex);
           });
  }

}

I wanted to change this like so:

  • log -- Test @start: ... when the test itself starts (ie. use BeforeTestExecutionCallback)
  • and use the BeforeEachCallback to mark the start of @BeforeEach execution(s) but only iff there is actually before-code being executed, as to avoid cluttering.

So the question is: How can i tell if there are actually 1..n @BeforeEach methods that are being executed?

I investigated the the ExtensionContext but came up empty.

elonderin
  • 509
  • 4
  • 12

1 Answers1

1

So the question is: How can i tell if there are actually 1..n @BeforeEach methods that are being executed?

As of JUnit Jupiter 5.4, there is no official way to find that out. That information is not exposed in any user-facing API: it's internal to the JUnit Jupiter TestEngine.

However, the new InvocationInterceptor extension API coming in JUnit Jupiter 5.5 will provide a way to determine if a @BeforeEach method is about to be executed.

Sam Brannen
  • 29,611
  • 5
  • 104
  • 136