JUnit 5 Extensions Model: Writing Custom @ExtendWith Extensions
JUnit 5's extension model replaces @RunWith and @Rule with a single, composable mechanism. You implement one or more callback interfaces—BeforeEachCallback, ParameterResolver, TestExecutionExceptionHandler, and others—register them with @ExtendWith, and JUnit injects them at the right lifecycle points. This post walks through building three real extensions from scratch.
JUnit 4 gave you @RunWith (one per class) and @Rule (multiple, but awkward). JUnit 5 replaced both with a unified extension model. Extensions are classes that implement any number of well-defined callback interfaces, and you compose them freely. One class can implement setup, parameter injection, and exception handling simultaneously.
Understanding extensions unlocks a level of test code reuse that @Before/@After alone can't achieve. Let's build some.
How the Extension API is Structured
JUnit 5 extensions live in the org.junit.jupiter.api.extension package. The extension model defines around 20 callback interfaces, each corresponding to a point in the test lifecycle:
| Interface | When it fires |
|---|---|
BeforeAllCallback |
Before any test in the class |
BeforeEachCallback |
Before each test method |
AfterEachCallback |
After each test method |
AfterAllCallback |
After all tests in the class |
BeforeTestExecutionCallback |
Immediately before the test body |
AfterTestExecutionCallback |
Immediately after the test body (before @AfterEach) |
ParameterResolver |
When a test method or constructor needs a parameter |
TestExecutionExceptionHandler |
When a test throws an exception |
TestInstanceFactory |
Controls how test instances are created |
TestInstancePostProcessor |
Called after the test instance is created |
You register extensions with @ExtendWith on the test class or method, or via @RegisterExtension as a field.
Building a Timing Extension
The simplest useful extension measures how long each test takes and logs slow tests. This implements BeforeTestExecutionCallback and AfterTestExecutionCallback:
import org.junit.jupiter.api.extension.*;
import java.util.logging.Logger;
public class TimingExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
private static final Logger LOG = Logger.getLogger(TimingExtension.class.getName());
private static final String START_TIME_KEY = "start time";
@Override
public void beforeTestExecution(ExtensionContext context) {
getStore(context).put(START_TIME_KEY, System.currentTimeMillis());
}
@Override
public void afterTestExecution(ExtensionContext context) {
long startTime = getStore(context).remove(START_TIME_KEY, long.class);
long duration = System.currentTimeMillis() - startTime;
String testName = context.getDisplayName();
if (duration > 500) {
LOG.warning(String.format("SLOW TEST: %s took %d ms", testName, duration));
} else {
LOG.info(String.format("%s took %d ms", testName, duration));
}
}
private ExtensionContext.Store getStore(ExtensionContext context) {
return context.getStore(
ExtensionContext.Namespace.create(getClass(), context.getRequiredTestMethod())
);
}
}The ExtensionContext.Store is the right way to pass state between callbacks within the same extension. Each extension instance may be shared across tests, so don't use instance fields for per-test state—use the Store with a unique namespace.
Apply it:
@ExtendWith(TimingExtension.class)
class OrderServiceTest {
@Test
void calculateDiscount_shouldReturn10PercentForPremiumUsers() {
// test body
}
}Building a Parameter Resolver
ParameterResolver lets your test methods declare parameters that JUnit will inject. This is how @TempDir and @Autowired (in Spring) work. Here's an extension that injects a pre-configured ObjectMapper:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.junit.jupiter.api.extension.*;
public class ObjectMapperExtension implements ParameterResolver {
private static final ObjectMapper MAPPER = createMapper();
private static ObjectMapper createMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
return mapper;
}
@Override
public boolean supportsParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) {
return parameterContext.getParameter().getType() == ObjectMapper.class;
}
@Override
public Object resolveParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) {
return MAPPER;
}
}Usage:
@ExtendWith(ObjectMapperExtension.class)
class UserSerializationTest {
@Test
void serializeUser_shouldProduceValidJson(ObjectMapper mapper) throws Exception {
User user = new User("alice", "alice@example.com");
String json = mapper.writeValueAsString(user);
assertThat(json).contains("\"email\":\"alice@example.com\"");
}
}The supportsParameter check is important — it tells JUnit whether your resolver handles a given parameter. If you return false, JUnit tries other resolvers (and ultimately fails if none match). Be specific: check the parameter type, and optionally check for an annotation on the parameter.
Building an Exception Handler with Retry Logic
TestExecutionExceptionHandler intercepts exceptions thrown during a test. You can inspect the exception, rethrow it, or swallow it (which marks the test as passed). A classic use case: retry flaky integration tests.
import org.junit.jupiter.api.extension.*;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RetryOnFailure {
int times() default 3;
}import org.junit.jupiter.api.extension.*;
import java.lang.reflect.Method;
public class RetryExtension implements TestExecutionExceptionHandler {
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable)
throws Throwable {
Method testMethod = context.getRequiredTestMethod();
RetryOnFailure retry = testMethod.getAnnotation(RetryOnFailure.class);
if (retry == null) {
throw throwable; // no annotation, rethrow
}
int maxAttempts = retry.times();
int attempt = getAttempt(context);
if (attempt < maxAttempts) {
incrementAttempt(context);
// Rethrowing triggers handleTestExecutionException again on the next attempt
// This works because JUnit re-invokes the handler for each attempt
testMethod.invoke(context.getRequiredTestInstance());
} else {
throw throwable;
}
}
private int getAttempt(ExtensionContext context) {
return context.getStore(ExtensionContext.Namespace.create(getClass()))
.getOrDefault(context.getUniqueId() + "_attempt", Integer.class, 0);
}
private void incrementAttempt(ExtensionContext context) {
int current = getAttempt(context);
context.getStore(ExtensionContext.Namespace.create(getClass()))
.put(context.getUniqueId() + "_attempt", current + 1);
}
}Usage:
@ExtendWith(RetryExtension.class)
class ExternalApiTest {
@Test
@RetryOnFailure(times = 3)
void fetchOrderStatus_shouldReturnDelivered() {
// may be flaky due to external service latency
}
}A production-grade retry extension would also log each attempt and track the attempt count in the Store more carefully — but this pattern shows the mechanism.
Composing Multiple Extensions
You can stack @ExtendWith declarations, or create a meta-annotation that bundles them:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(TimingExtension.class)
@ExtendWith(ObjectMapperExtension.class)
public @interface IntegrationTest {}Then:
@IntegrationTest
class PaymentGatewayTest {
@Test
void chargeCard_shouldReturn200(ObjectMapper mapper) {
// ObjectMapper injected, timing logged
}
}This is the idiomatic way to build test utilities in JUnit 5. Define extension behavior once, compose it with annotations, and apply the meta-annotation on test classes.
@RegisterExtension for Programmatic Control
@ExtendWith applies the same extension instance to all tests in a class. @RegisterExtension lets you create the extension as a field, giving you constructor control and per-class vs. per-test lifecycle options:
class DatabaseTest {
@RegisterExtension
static final DatabaseExtension db = new DatabaseExtension("testdb");
@Test
void insertUser_shouldBeRetrievable() {
db.getConnection().execute("INSERT INTO users ...");
// ...
}
}Static fields use class-level lifecycle (one instance for all tests). Instance fields use per-test lifecycle (fresh instance per test). Use static for expensive resources (database connections, embedded servers) and instance fields when each test needs an isolated state.
Extension Context and Stores
Every callback receives an ExtensionContext. Key things you can get from it:
context.getRequiredTestMethod() // the Method being tested
context.getRequiredTestClass() // the test class
context.getRequiredTestInstance() // the test object instance
context.getDisplayName() // human-readable name
context.getTags() // @Tag values on this test
context.getConfigurationParameter("key") // from junit-platform.properties
context.getStore(namespace) // key-value store scoped to namespaceStores are scoped by namespace. Use ExtensionContext.Namespace.create(ExtensionClass.class, testMethod) for per-test isolation. Use ExtensionContext.Namespace.create(ExtensionClass.class) for class-level sharing.
When to Write a Custom Extension
Write a custom extension when you find yourself copying the same setup/teardown logic across multiple test classes, when you need parameter injection that your framework doesn't provide, or when you want to enforce test conventions (like the timing example — slow tests should be visible).
Avoid writing extensions for logic that should live in test fixtures or test base classes. Extensions are powerful but they add indirection. If you only use a behavior in one test class, keep it in that class.
Testing Your Extension
Extensions themselves need tests. The pattern is to write a test class that uses the extension and verify the side effects:
@ExtendWith(TimingExtension.class)
class TimingExtensionTest {
@Test
void fastTest_shouldNotLogWarning() throws InterruptedException {
// runs fast — TimingExtension should log INFO, not WARNING
}
@Test
void slowTest_shouldLogWarning() throws InterruptedException {
Thread.sleep(600); // deliberately slow
}
}For more complex extensions, use the JUnit 5 extension testing utilities or verify behavior through log capture or System.out interception.
Summary
JUnit 5's extension model is composable, explicit, and replaces everything JUnit 4 used @RunWith and @Rule for. Implement BeforeEachCallback/AfterEachCallback for setup and teardown logic, ParameterResolver for injecting test fixtures, and TestExecutionExceptionHandler for retry and error handling. Use ExtensionContext.Store for per-test state instead of instance fields. Compose multiple extensions with meta-annotations to keep test classes clean.