Video in progress

Strong Middle 🧪 Testing

How does the JUnit 5 extension model work, and give an example of a case where you wrote an extension yourself.

JUnit 5 has extensions instead of runners and rules: they implement interfaces like BeforeEachCallback, ParameterResolver and TestExecutionExceptionHandler, and are called at the relevant point in the test lifecycle. They're attached to a class with @ExtendWith, and several can sit side by side without trouble.

📖 Answer

In JUnit 4 you could put only one @RunWith on a class, and using SpringRunner together with MockitoJUnitRunner was painful. In JUnit 5, SpringExtension and MockitoExtension sit side by side.

A real example: put the test name into the MDC before each test to separate the logs, and give the test a ready-made Clock:

public class TestClockExtension implements BeforeEachCallback, ParameterResolver {

    private static final ExtensionContext.Namespace NS = ExtensionContext.Namespace.create(TestClockExtension.class);

    @Override
    public void beforeEach(ExtensionContext ctx) {
        MDC.put("test", ctx.getDisplayName());
        ctx.getStore(NS).put("clock", new MutableClock(Instant.parse("2026-01-01T00:00:00Z")));
    }

    @Override
    public boolean supportsParameter(ParameterContext p, ExtensionContext e) {
        return p.getParameter().getType() == MutableClock.class;
    }

    @Override
    public Object resolveParameter(ParameterContext p, ExtensionContext e) {
        return e.getStore(NS).get("clock");
    }
}

@ExtendWith(TestClockExtension.class)
class BillingTest {
    @Test
    void chargesMonthly(MutableClock clock) { ... }
}

ExtensionContext.Store is the right place to keep state. Don't write state into the extension's instance fields: with parallel execution, one extension object may serve several tests. The Store is isolated at the test level, and when the scope ends, ExtensionContext.Store.CloseableResource values close themselves (in JUnit 5.13+ a plain AutoCloseable works too).