elonderin
elonderin

Reputation: 537

junit5: howto introspect if a test is actually augmented with @Before/AfterEach methods

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:

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.

Upvotes: 1

Views: 144

Answers (1)

Sam Brannen
Sam Brannen

Reputation: 31247

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.

Upvotes: 1

Related Questions