Skip to content
javahacks.dev
JUnit

JUnit Extension Model Explained With Custom Examples

Understand the JUnit Jupiter extension model: extension points, ExtendWith, parameter resolvers, callbacks and conditions, with three custom examples.

8 min read
Summarize in AI
Flat illustration of a JUnit test run with one failing test, with the JUnit5, Spring Boot and GitHub Actions logos.

@ExtendWith(MockitoExtension.class), @ExtendWith(SpringExtension.class), @Testcontainers, @TempDir: all of these are the same mechanism. JUnit Jupiter keeps a small core and moves everything else, mocking, dependency injection, container lifecycle, retry, into extensions, small classes that hook into the test lifecycle. It replaced two JUnit 4 features, runners and rules, which could not be combined and had separate APIs. Learning the extension model pays twice: you can read what the libraries you use are doing, and you can write the odd extension your own project needs, usually thirty lines. This post covers the extension points, three custom examples that each use a different one, how to register them and how to keep state. The test lifecycle they hook into is explained in JUnit lifecycle annotations and execution order. The API is the same in JUnit 5 and JUnit 6.

How the model works

An extension is a class that implements one or more extension point interfaces from org.junit.jupiter.api.extension. JUnit finds the registered extensions for a test and calls the matching methods at defined moments. Each interface represents one moment:

InterfaceWhen it is calledTypical use
ExecutionConditionBefore a test or class is runEnable or disable tests dynamically
BeforeAllCallback, AfterAllCallbackAround the whole classStart and stop a shared resource
BeforeEachCallback, AfterEachCallbackAround each testReset state, start a transaction
BeforeTestExecutionCallback, AfterTestExecutionCallbackImmediately around the test method itselfTiming, tracing
ParameterResolverWhen a method needs an argumentInject a mock, a temp directory, a fixture
TestInstancePostProcessorAfter the test instance is createdField injection
TestExecutionExceptionHandlerWhen a test throwsTranslate or swallow an exception
TestWatcherAfter a test finishesReport results, take a screenshot on failure
InvocationInterceptorAround each invocationRetry, run on another thread

Each callback receives an ExtensionContext, an object describing the current class and method, the store for extension state and the configuration. The extension never extends a test class or runs inside it: it observes and influences from outside, which is why they compose.

Registering an extension

Three ways, depending on how much control you need:

java
@ExtendWith(TimingExtension.class)               // declarative: the class is instantiated for you
class OrderServiceTest { }
java
class OrderServiceTest {
    @RegisterExtension                            // programmatic: you build the instance and can configure it
    static final DatabaseExtension db = new DatabaseExtension("jdbc:h2:mem:orders");
}

And automatic registration by listing the class in META-INF/services/org.junit.jupiter.api.extension.Extension with junit.jupiter.extensions.autodetection.enabled=true, for extensions that should apply to every test in a module. The declarative form is the common one. Use @RegisterExtension when the extension needs constructor arguments or when tests need to call its methods; the field must be non private, and static if the extension has to take part in @BeforeAll callbacks.

@ExtendWith can also appear on a method, a parameter or in a meta annotation. Composing annotations to bundle extensions is a good way to give your team one name for a setup, as shown in writing composed annotations in JUnit.

Example 1: a timing extension

The smallest useful extension implements two callbacks and keeps the start time in the store. It prints how long each test took and flags slow ones:

src/test/java/dev/javahacks/junit/TimingExtension.javajava
package dev.javahacks.junit;

import org.junit.jupiter.api.extension.*;

import java.lang.reflect.Method;
import java.time.Duration;

public class TimingExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {

    private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create(TimingExtension.class);
    private static final Duration SLOW = Duration.ofMillis(500);

    @Override
    public void beforeTestExecution(ExtensionContext context) {
        context.getStore(NAMESPACE).put(key(context), System.nanoTime());
    }

    @Override
    public void afterTestExecution(ExtensionContext context) {
        long start = context.getStore(NAMESPACE).remove(key(context), long.class);
        Duration took = Duration.ofNanos(System.nanoTime() - start);
        String flag = took.compareTo(SLOW) > 0 ? "  <-- SLOW" : "";
        System.out.printf("%s took %d ms%s%n", context.getDisplayName(), took.toMillis(), flag);
    }

    private static String key(ExtensionContext context) {
        Method method = context.getRequiredTestMethod();
        return method.getDeclaringClass().getName() + "#" + method.getName();
    }
}
java
@ExtendWith(TimingExtension.class)
class ReportServiceTest {

    @Test
    void buildsTheMonthlyReport() throws Exception {
        Thread.sleep(700);
    }
}
Text
buildsTheMonthlyReport() took 703 ms  <-- SLOW

The extension instance is shared, so it must not keep per test state in fields; two tests running in parallel would overwrite each other. The **ExtensionContext.Store** is the right place. It is a key value map with a namespace, scoped to the context it came from: a method context for one test, a class context for the whole class. Values stored on a class context are visible to its methods through the parent chain, and a stored value that implements AutoCloseable (or the older CloseableResource) is closed automatically when that context ends, which makes the store the idiom for resource lifecycle.

Example 2: a parameter resolver

ParameterResolver is the extension point behind @TempDir, TestInfo, mocks and most of what makes tests concise. It decides whether it can supply a given parameter, and then supplies it. This one injects a fresh Clock fixed at a known instant into any test method that asks for one:

src/test/java/dev/javahacks/junit/FixedClockExtension.javajava
package dev.javahacks.junit;

import org.junit.jupiter.api.extension.*;

import java.lang.annotation.*;
import java.time.*;

public class FixedClockExtension implements ParameterResolver {

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.PARAMETER)
    public @interface At {
        String value();                      // an ISO instant such as 2026-12-31T23:30:00Z
    }

    @Override
    public boolean supportsParameter(ParameterContext parameter, ExtensionContext context) {
        return parameter.getParameter().getType() == Clock.class;
    }

    @Override
    public Object resolveParameter(ParameterContext parameter, ExtensionContext context) {
        Instant instant = parameter.findAnnotation(At.class)
                .map(a -> Instant.parse(a.value()))
                .orElse(Instant.parse("2026-01-01T00:00:00Z"));
        return Clock.fixed(instant, ZoneOffset.UTC);
    }
}
java
@ExtendWith(FixedClockExtension.class)
class InvoiceServiceTest {

    @Test
    void dueDateIsThirtyDaysOut(@FixedClockExtension.At("2026-12-31T23:30:00Z") Clock clock) {
        var service = new InvoiceService(clock);

        assertEquals(LocalDate.of(2027, 1, 30), service.issue(new Order(1)).dueOn());
    }
}

The two methods are the whole contract. supportsParameter answers whether this extension handles the parameter, and if no registered resolver says yes, JUnit fails with No ParameterResolver registered for parameter [java.time.Clock clock]. If two resolvers say yes for the same parameter, JUnit fails instead of guessing, which is why resolvers should be narrow: the type check above plus an optional annotation. The parameter annotation carries the test specific value, the injected instant, right at the point of use, which is more readable than a field set in @BeforeEach. This is the mechanism covered in JUnit ParameterResolver and callbacks.

Example 3: a condition and an exception handler

ExecutionCondition runs before a test and can disable it. This extension skips tests annotated with @RequiresDocker when no Docker daemon answers, so the suite passes on machines without it instead of failing noisily:

src/test/java/dev/javahacks/junit/DockerCondition.javajava
public class DockerCondition implements ExecutionCondition {

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE, ElementType.METHOD})
    @ExtendWith(DockerCondition.class)
    public @interface RequiresDocker {}

    @Override
    public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
        boolean available = dockerResponds();
        return available
                ? ConditionEvaluationResult.enabled("docker is available")
                : ConditionEvaluationResult.disabled("docker is not running");
    }

    private boolean dockerResponds() {
        try {
            Process p = new ProcessBuilder("docker", "info").redirectErrorStream(true).start();
            return p.waitFor(5, java.util.concurrent.TimeUnit.SECONDS) && p.exitValue() == 0;
        } catch (Exception e) {
            return false;
        }
    }
}

Notice that the annotation carries @ExtendWith(DockerCondition.class) itself. A test only writes @RequiresDocker, and the extension registers through the meta annotation, the same technique @SpringBootTest and @Testcontainers use. Skipped tests are reported as skipped with the reason string, not hidden.

TestExecutionExceptionHandler intercepts a failing test, which can be used to enrich the failure. This one attaches the application log to the error message:

java
public class AttachLogOnFailure implements TestExecutionExceptionHandler {
    @Override
    public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
        System.err.println("--- application log for " + context.getDisplayName() + " ---");
        System.err.println(TestLogBuffer.drain());
        throw throwable;                         // rethrow: the test still fails
    }
}

Rethrowing is important. An extension that swallows the exception makes a failing test pass, a legitimate technique for something like a retry extension and a dangerous bug anywhere else.

Order and scope

When several extensions register for the same point, JUnit calls them in registration order, with After callbacks in the reverse order, like nested wrappers. Extensions registered on a class are inherited by its methods; ones registered on a method apply only to it; and a parameter level @ExtendWith applies to that parameter only. @RegisterExtension fields are ordered with @Order.

Instances are created once per registration, so they should be stateless or keep state in the Store, as above. An extension that is registered on a class used by parallel tests will be called concurrently, and any instance field is shared across the calls.

How the libraries you use are built

Reading the list of extension points makes the library annotations unremarkable. MockitoExtension is a BeforeEachCallback that initialises @Mock fields, an AfterEachCallback that validates strict stubs and a ParameterResolver for mock parameters, as shown in using Mockito with JUnit 5 extensions. SpringExtension is a TestInstancePostProcessor that injects @Autowired fields, a ParameterResolver for constructor and method injection and a set of callbacks that manage the cached application context and transaction. @TempDir is a built in ParameterResolver plus cleanup through the store. Testcontainers' @Container is a BeforeAllCallback and AfterAllCallback pair that starts and stops containers around the class.

Testing an extension

An extension is code with branches, and JUnit provides a way to test it: the JUnit Platform Test Kit, which runs a test class programmatically and returns the results:

java
@Test
void slowTestsAreFlagged() {
    EngineTestKit.engine("junit-jupiter")
            .selectors(DiscoverySelectors.selectClass(SlowSample.class))
            .execute()
            .testEvents()
            .assertStatistics(stats -> stats.started(1).succeeded(1));
}

For the condition, assert that a sample test annotated with @RequiresDocker is reported as skipped when the condition returns disabled, by stubbing the docker check. For a resolver, a plain unit test calling supportsParameter and resolveParameter with mocked contexts covers the logic, and one Test Kit run covers the wiring.

Pitfalls

State in fields. The commonest bug. Use the store.

Overly broad resolvers. A resolver that supports every String parameter conflicts with the next one; match on type and annotation.

Static registration of expensive extensions. An extension that starts a container for every class, when one per module would do, slows the suite; scope the resource to the root context with the store's getOrComputeIfAbsent on the root, which is the pattern for a shared singleton.

Hiding failures. An extension that catches and reports without rethrowing masks real test failures.

Reaching for an extension too early. A helper method or a @BeforeEach is simpler when the logic is used in one class.

When this does not apply

If a project is still on JUnit 4, the equivalents are rules and runners, and the migration is covered in migrating JUnit 4 rules and extensions to JUnit 5. For one off logic in one test class, write a normal method. The primary references are the JUnit user guide chapter on the extension model and the Javadoc for the extension API.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.