You write @ExtendWith(SomeExtension.class), run the test, and one of three things happens: nothing (the extension never fires), No ParameterResolver registered for parameter [java.lang.String arg0], or two extensions fight over the same parameter. All three come from not knowing what @ExtendWith actually registers, where it can go, and in what order the registered extensions run.
This page answers the @ExtendWith question directly: what it does, class versus method versus parameter level, @Target, @Repeatable and @Inherited, how it differs from @RegisterExtension and ServiceLoader auto-registration, the order extensions run in, and how composed annotations such as @MockitoSettings and @SpringBootTest hide an @ExtendWith. Then you write three small extensions yourself (a timing extension, a parameter resolver and an exception handler) and see what changed between JUnit 5 and JUnit 6. Everything quoted below was run; the code is in the companion module extendwith.
Versions tested. JUnit Jupiter 6.1.3 (latest GA on Maven Central; the 6.x line went GA with 6.0.0 on 30 September 2025, 6.1.3 shipped 7 August 2026) and JUnit Jupiter 5.14.4 (latest 5.x) with the same sources through a second Maven profile. Mockito 5.24.0, JDK 25 (Temurin 25.0.5), Maven 3.9. Version numbers come from maven-metadata.xml; dates from the JUnit release notes.
What is JUnit @ExtendWith?
In JUnit 5 and 6, the @ExtendWith annotation is the primary way to register one or more Extensions for a test class or a specific test method.
Think of an extension as a “plugin” for your tests. Instead of JUnit being a closed system, it provides Extension Points—specific moments in the test lifecycle (like before a test starts, after it fails, or when a parameter needs to be resolved). The @ExtendWith annotation tells JUnit: “Hey, use this specific class to intercept these lifecycle events for me.”
The diagram is the whole mental model: the annotation holds a class literal, not an object. JUnit creates the extension itself, so an extension registered this way needs a no-argument constructor. When you need to hand it constructor arguments, you register an instance yourself with @RegisterExtension (below).
The annotation is declared with @Target covering four element types, is @Repeatable and is @Inherited. Those are facts read from the annotation at runtime, not remembered:
@ExtendWith @Target = [FIELD, METHOD, PARAMETER, TYPE]
@ExtendWith @Repeatable = Extensions
@ExtendWith @Inherited = true
@Extensions @Target = [FIELD, METHOD, PARAMETER, TYPE]
@ExtendWith value() type = Class[]
StackedFixture has two @ExtendWith; the compiler stored them as one @Extensions
Source: ExtendWithTest.java, written to 07-annotation-facts.txt. Two practical consequences. First, @Repeatable means you can stack @ExtendWith lines and the compiler wraps them in an @Extensions container for you. Second, @Inherited means a subclass of an annotated test class gets the extension too.
Key Advantages: Composition over Inheritance
- True Composability: In JUnit 4, you were limited to a single
@RunWithannotation. JUnit 5 allows you to stack as many@ExtendWithdeclarations as you need. - Granular Scope: You can apply extensions to an entire class, a nested inner class, or even a single
@Testmethod. - Unified API: It eliminates the confusing distinction between
Runners,MethodRules, andTestRules.
JUnit 4 @RunWith vs. JUnit 5 @ExtendWith
| Feature | JUnit 4 (@RunWith / @Rule) | JUnit 5 (@ExtendWith) |
| Cardinality | Only one Runner per class | Multiple extensions allowed |
| Integration | Difficult to combine frameworks | Seamlessly combine Mockito, Spring, etc. |
| Logic Reuse | Done via Rules and Base Classes | Done via reusable Extension classes |
| Example | MockitoJUnitRunner.class | MockitoExtension.class |
Class, method, nested class or parameter: where @ExtendWith can go
The fixture below puts FirstExtension on the class, SecondExtension on one method, and has a @Nested class. Each extension logs its callbacks into an EventLog that the test prints (LevelsFixture.java).
package com.ankurm.tutorials.junit.extendwith.fixtures;
import com.ankurm.tutorials.junit.extendwith.ext.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.io.*;
/** Where can @ExtendWith go? Class, method, nested class. */
@ExtendWith(FirstExtension.class)
public class LevelsFixture {
@Test
void classLevelOnly() {
EventLog.add(" test classLevelOnly");
}
@Test
@ExtendWith(SecondExtension.class)
void methodLevelToo() {
EventLog.add(" test methodLevelToo");
}
@Nested
class Inner {
@Test
void insideNested() {
EventLog.add(" test insideNested");
}
}
}
LevelsFixture (@ExtendWith(FirstExtension) on the class; SecondExtension on one method)
FirstExtension created
FirstExtension.beforeAll LevelsFixture
FirstExtension.beforeEach classLevelOnly()
test classLevelOnly
FirstExtension.afterEach classLevelOnly()
SecondExtension created
FirstExtension.beforeEach methodLevelToo()
SecondExtension.beforeEach methodLevelToo()
test methodLevelToo
SecondExtension.afterEach methodLevelToo()
FirstExtension.afterEach methodLevelToo()
FirstExtension.beforeAll Inner
FirstExtension.beforeEach insideNested()
test insideNested
FirstExtension.afterEach insideNested()
FirstExtension.afterAll Inner
FirstExtension.afterAll LevelsFixture
-- results
classLevelOnly() -> SUCCESSFUL
methodLevelToo() -> SUCCESSFUL
insideNested() -> SUCCESSFUL
-- results
Read the log top to bottom. FirstExtension fires for all three tests, including the one inside Inner: a class-level extension covers nested classes, and beforeAll fires again for the nested class. SecondExtension was created lazily and fires only around methodLevelToo(). Transcript: 01-levels.txt.
The fourth place is a parameter. Putting @ExtendWith on a parameter registers a ParameterResolver for that parameter only (ParameterLevelFixture.java):
package com.ankurm.tutorials.junit.extendwith.fixtures;
import com.ankurm.tutorials.junit.extendwith.ext.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.io.*;
/** @ExtendWith directly on a parameter registers the resolver for that parameter only. */
public class ParameterLevelFixture {
@Test
void keyFromParameterAnnotation(@ExtendWith(ApiKeyResolver.class) @ApiKey("billing") String key) {
EventLog.add(" test got " + key);
}
}
ParameterLevelFixture (@ExtendWith(ApiKeyResolver) on the parameter itself)
ApiKeyResolver.resolveParameter parameter 0 -> key for 'billing'
test got sk-test-billing
keyFromParameterAnnotation(String) -> SUCCESSFUL
Putting it at the wrong level. AParameterResolveror a callback registered on one method does nothing for the other methods of the class, and@ExtendWithon a field only means something for the extension kinds that support field registration. If an extension seems to be ignored, first check that the annotation sits on the element JUnit is actually executing.
Going deeper: JUnit user guide, extension model; @RegisterExtension, static versus instance fields.
Write your first extension: time every test
An extension is a class that implements one or more extension-point interfaces. Start with the smallest useful one: record the start time in beforeEach, report the duration in afterEach. State goes into the ExtensionContext.Store, not into a field, because one extension instance serves many tests (TimingExtension.java).
package com.ankurm.tutorials.junit.extendwith.ext;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
/**
* The first extension of the article: it times every test and reports the duration.
* Two callbacks, one piece of state, kept in the ExtensionContext.Store so it belongs to one test, not to the extension instance.
*/
public class TimingExtension implements BeforeEachCallback, AfterEachCallback {
private static final Namespace NAMESPACE = Namespace.create(TimingExtension.class);
private static final String START = "start";
@Override
public void beforeEach(ExtensionContext context) {
context.getStore(NAMESPACE).put(START, System.nanoTime());
EventLog.add("TimingExtension.beforeEach " + context.getDisplayName());
}
@Override
public void afterEach(ExtensionContext context) {
long start = context.getStore(NAMESPACE).remove(START, long.class);
long millis = (System.nanoTime() - start) / 1_000_000;
EventLog.add("TimingExtension.afterEach " + context.getDisplayName() + " took " + millis + " ms");
}
}
Apply it with @ExtendWith(TimingExtension.class) (fixture: TimingFixture.java). Run on JUnit 6.1.3:
TimingFixture (@ExtendWith(TimingExtension.class))
TimingExtension.beforeEach fast()
test fast
TimingExtension.afterEach fast() took N ms
TimingExtension.beforeEach slow()
test slow (slept 30 ms)
TimingExtension.afterEach slow() took N ms
-- results
fast() -> SUCCESSFUL
slow() -> SUCCESSFUL
ComposedFixture (@TimedTest = @Test + @ExtendWith(TimingExtension))
TimingExtension.beforeEach timedWithOneAnnotation()
test timedWithOneAnnotation
TimingExtension.afterEach timedWithOneAnnotation() took N ms
-- results
timedWithOneAnnotation() -> SUCCESSFUL
(the millisecond figure is masked as N; the test asserts that slow() took at least 30 ms)
The duration is masked as N in the committed transcript because it differs on every run; the test asserts that slow(), which sleeps 30 ms, reports at least 30. Transcript: 04-timing-extension.txt.
To avoid repeating @ExtendWith on every class you can fold it into your own annotation. @TimedTest below is @Test plus @ExtendWith(TimingExtension.class), and the output of ComposedFixture above shows it behaves identically (TimedTest.java).
package com.ankurm.tutorials.junit.extendwith.ext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** A composed annotation: @Test plus @ExtendWith(TimingExtension.class) under one name. */
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Test
@ExtendWith(TimingExtension.class)
public @interface TimedTest {
}
Going deeper: JUnit 6 extensions model, step by step builds a similar logger and covers the full extension-point reference; the @BeforeEach and @AfterEach guide covers the methods these callbacks wrap.
Second extension: inject a parameter with ParameterResolver
A ParameterResolver answers two questions: do I support this parameter, and what value goes in it. This one supports String parameters annotated @ApiKey (ApiKeyResolver.java, annotation ApiKey.java).
package com.ankurm.tutorials.junit.extendwith.ext;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;
/** Second extension of the article: it hands a value to any String parameter annotated @ApiKey. */
public class ApiKeyResolver implements ParameterResolver {
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
return parameterContext.isAnnotated(ApiKey.class)
&& parameterContext.getParameter().getType() == String.class;
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
String name = parameterContext.findAnnotation(ApiKey.class).orElseThrow().value();
EventLog.add("ApiKeyResolver.resolveParameter parameter " + parameterContext.getIndex() + " -> key for '" + name + "'");
return "sk-test-" + name;
}
}
The fixture has two working tests and one that forgets the annotation (ResolverFixture.java):
ResolverFixture (@ExtendWith(ApiKeyResolver.class) on the class)
ApiKeyResolver.resolveParameter parameter 0 -> key for 'default'
test got sk-test-default
ApiKeyResolver.resolveParameter parameter 0 -> key for 'payments'
test got sk-test-payments
unannotatedParameter(String) -> FAILED (ParameterResolutionException: No ParameterResolver registered for parameter [java.lang.String arg0] in method [void com.ankurm.tutorials.junit.extendwith.fixtures.ResolverFixture.unannotatedParameter(java.lang.String)].)
defaultKey(String) -> SUCCESSFUL
namedKey(String) -> SUCCESSFUL
That unannotatedParameter failure is the message from the start of this page: no resolver supports the parameter, so JUnit refuses to guess. Now the second failure. If two registered resolvers both support one parameter, JUnit does not pick one (CompetingResolversFixture.java):
CompetingResolversFixture (two resolvers both support the parameter)
ambiguous(String) -> FAILED (ParameterResolutionException: Discovered multiple competing ParameterResolvers for parameter [java.lang.String arg0] in method [void com.ankurm.tutorials.junit.extendwith.fixtures.CompetingResolversFixture.ambiguous(java.lang.String)]: com.ankurm.tutorials.junit.extendwith.ext.ApiKeyResolver@HASH, com.ankurm.tutorials.junit.extendwith.ext.OtherApiKeyResolver@HASH)
MakesupportsParameternarrow. A resolver that says yes to everyStringwould collide with any other resolver and with parameterized tests. Test for your own annotation or a type only you own, asApiKeyResolverdoes. The object hash codes in the second message are masked as@HASHin the transcript (05-parameter-resolver.txt).
Third extension: handle an exception with TestExecutionExceptionHandler
A TestExecutionExceptionHandler sees every exception thrown by the test method and can swallow it, replace it or rethrow it. This one turns a simulated network timeout into an aborted test and leaves every other exception alone (NetworkTimeoutHandler.java).
package com.ankurm.tutorials.junit.extendwith.ext;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.opentest4j.TestAbortedException;
/**
* Third extension of the article: a test that dies of a network timeout is reported as aborted (not failed);
* every other exception is rethrown untouched, so real failures stay failures.
*/
public class NetworkTimeoutHandler implements TestExecutionExceptionHandler {
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
if (throwable instanceof NetworkTimeoutException) {
EventLog.add("NetworkTimeoutHandler swallowed " + throwable.getClass().getSimpleName() + " in " + context.getDisplayName());
throw new TestAbortedException("remote service unavailable: " + throwable.getMessage(), throwable);
}
EventLog.add("NetworkTimeoutHandler rethrowing " + throwable.getClass().getSimpleName() + " in " + context.getDisplayName());
throw throwable;
}
}
Four tests in ExceptionHandlerFixture.java: a timeout, a real bug, a failed assertion, and a pass.
ExceptionHandlerFixture (@ExtendWith(NetworkTimeoutHandler.class))
test passes
NetworkTimeoutHandler swallowed NetworkTimeoutException in remoteServiceTimesOut()
NetworkTimeoutHandler rethrowing AssertionFailedError in assertionStillFails()
NetworkTimeoutHandler rethrowing IllegalStateException in realBug()
-- results
passes() -> SUCCESSFUL
remoteServiceTimesOut() -> ABORTED (TestAbortedException: remote service unavailable: no answer from payments after 2000 ms)
assertionStillFails() -> FAILED (AssertionFailedError: expected: <4> but was: <5>)
realBug() -> FAILED (IllegalStateException: total is negative)
The timeout is reported as ABORTED, which CI shows as skipped, while the IllegalStateException and the AssertionFailedError stay FAILED. Transcript: 06-exception-handler.txt.
Do not hide real failures. Rethrowing everything you do not recognise, as the handler does, is the important line. An exception handler that swallows broadly turns a red build green, and the build then lies. Also note that this interface only sees exceptions from the test method; exceptions from@BeforeEachand the other lifecycle methods go toLifecycleMethodExecutionExceptionHandler, which exists in both 5.14.4 and 6.1.3.
Going deeper: advanced extensions builds a retry extension, soft assertions and a TestTemplate on these same ideas.
JUnit Extension Lifecycle at a Glance
Understanding when your code executes is critical for debugging. LifecycleExtension implements all six lifecycle callbacks next to a class with its own @BeforeAll, @BeforeEach, @AfterEach and @AfterAll (LifecycleExtension.java, LifecycleFixture.java). The captured order:
BeforeAllCallback
@BeforeAll
BeforeEachCallback
@BeforeEach
BeforeTestExecutionCallback
@Test
AfterTestExecutionCallback
@AfterEach
AfterEachCallback
@AfterAll
AfterAllCallback
The diagram restates that transcript. The point that bites in practice: an extension’s beforeEach runs before your @BeforeEach, so an extension cannot rely on fields your @BeforeEach sets up. Transcript: 13-lifecycle-order.txt.
The original ASCII sketch of the lifecycle
This is the flow from the earlier version of this post, kept for reference. The captured order above is the verified version.
[ Test Discovery ]
│
▼
[ BeforeAllCallback ]
(Once per class)
│
▼
[ BeforeEachCallback ]
(Before every @Test)
│
▼
[ BeforeTestExecutionCallback ]
(Immediately before test method)
│
▼
( @Test Method )
│
▼
[ AfterTestExecutionCallback ]
(Immediately after test method)
│
▼
[ AfterEachCallback ]
(After every @Test)
│
▼
[ AfterAllCallback ]
(Once per class)</code>
The sketch is a conceptual diagram and was not generated by code, so there is no repo file for it; the verified order is in 13-lifecycle-order.txt.
Order of registration: who runs first
Extensions run in the order they were registered. Declare @ExtendWith(First) then @ExtendWith(Second) and the before-callbacks run First, Second, while the after-callbacks run Second, First.
The picture is the first block of the transcript below. The other blocks compare the other ways of declaring order (02-order.txt).
StackedFixture @ExtendWith(First) then @ExtendWith(Second)
FirstExtension created
SecondExtension created
FirstExtension.beforeEach test()
SecondExtension.beforeEach test()
SecondExtension.afterEach test()
FirstExtension.afterEach test()
ArrayFixture @ExtendWith({Second, First})
SecondExtension created
FirstExtension created
SecondExtension.beforeEach test()
FirstExtension.beforeEach test()
FirstExtension.afterEach test()
SecondExtension.afterEach test()
RegisterExtensionOrderFixture first=@Order(2), second=@Order(1)
FirstExtension created
SecondExtension created
SecondExtension.beforeEach test()
FirstExtension.beforeEach test()
FirstExtension.afterEach test()
SecondExtension.afterEach test()
MixedFixture @ExtendWith(Second) on the class, @RegisterExtension First field
SecondExtension created
FirstExtension created
SecondExtension.beforeEach test()
FirstExtension.beforeEach test()
FirstExtension.afterEach test()
SecondExtension.afterEach test()
DuplicateFixture @ExtendWith(First) on the class AND on the method
FirstExtension created
FirstExtension.beforeEach test()
FirstExtension.afterEach test()
Four things to read from it. Stacked @ExtendWith lines run in the order written. The array form @ExtendWith({Second, First}) runs in array order. With @RegisterExtension fields you control order with @Order: the lower number goes first, so @Order(1) on second beat @Order(2) on first. In the mixed case the class-level @ExtendWith extension ran before the @RegisterExtension field. And the same extension class named on the class and on a method was created once and fired once.
Fixtures: StackedFixture.java, ArrayFixture.java, RegisterExtensionOrderFixture.java, MixedFixture.java, DuplicateFixture.java.
@ExtendWith vs @RegisterExtension vs ServiceLoader
| Mechanism | Where | Constructor arguments | Use when |
|---|---|---|---|
@ExtendWith | class, method, parameter, field | no, JUnit calls the no-argument constructor | the extension needs no configuration |
@RegisterExtension | static or instance field | yes, you build the object | the extension takes values or exposes methods to the test |
| ServiceLoader | META-INF/services file | no | every test in the module should get the extension; off by default |
The second row needs the extension object in the test class. This is the earlier post’s TempDirectoryExtension (which that post used without showing; this version only logs) registered through a static field (RegisterExtensionFixture.java):
package com.ankurm.tutorials.junit.extendwith.fixtures;
import com.ankurm.tutorials.junit.extendwith.ext.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.io.*;
public class RegisterExtensionFixture {
@RegisterExtension
static TempDirectoryExtension tempDir = new TempDirectoryExtension("/custom/path/logs");
@Test
void testLogCreation() {
EventLog.add("Using directory: " + tempDir.getPath());
}
}
The third row is the surprising one. A file named org.junit.jupiter.api.extension.Extension under META-INF/services lists the extension class (org.junit.jupiter.api.extension.Extension). Nothing happens until you switch auto-detection on with junit.jupiter.extensions.autodetection.enabled=true. The same PlainFixture, which has no annotations, run both ways:
ServiceLoader, junit.jupiter.extensions.autodetection.enabled not set (PlainFixture)
test
ServiceLoader, junit.jupiter.extensions.autodetection.enabled=true (PlainFixture)
AutoRegisteredExtension.beforeEach test()
test
Auto-registered extensions are global. Once auto-detection is on, every test class on the classpath gets the extension, including tests that never asked for it. That is the right tool for a company-wide logging extension and the wrong one for anything with side effects. Transcript: 03-registration.txt.
Going deeper: @RegisterExtension in depth.
Composed annotations: @MockitoSettings, @SpringBootTest and your own
Many annotations you already use are @ExtendWith in disguise. Reading the class files with javap -v (script versions.sh):
== Is the annotation itself an @ExtendWith? (javap -v, RuntimeVisibleAnnotations)
-- @MockitoSettings (mockito-junit-jupiter-5.24.0.jar)
Lorg/junit/jupiter/api/extension/ExtendWith;
Lorg/mockito/junit/jupiter/MockitoExtension;
-- @SpringJUnitConfig (spring-test-7.0.10.jar)
Lorg/junit/jupiter/api/extension/ExtendWith;
Lorg/springframework/test/context/junit/jupiter/SpringExtension;
-- @SpringBootTest (spring-boot-test-4.1.2.jar)
Lorg/junit/jupiter/api/extension/ExtendWith;
Lorg/springframework/test/context/junit/jupiter/SpringExtension;
Each annotation carries an ExtendWith annotation naming its extension (MockitoExtension for @MockitoSettings, SpringExtension for @SpringJUnitConfig and @SpringBootTest; spring-test 7.0.10, spring-boot-test 4.1.2). So @SpringBootTest already registers SpringExtension and an explicit @ExtendWith(SpringExtension.class) next to it is redundant. Your own @TimedTest from earlier works the same way. Transcript: 10-composed-annotations.txt.
Integrating Mockito with @ExtendWith
The MockitoExtension automatically initializes mocks and manages the mock session lifecycle.
Step 1: Add the Dependency (Maven)
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.23.0</version>
<scope>test</scope>
</dependency>
The module uses version 5.24.0 (the earlier post said 5.23.0). The pom.xml: pom.xml.
Step 2: Implement the Test
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private PaymentGateway paymentGateway;
@InjectMocks
private OrderService orderService;
@Test
void shouldProcessPaymentSuccessfully() {
when(paymentGateway.authorize(100.0)).thenReturn(true);
boolean result = orderService.processOrder(100.0);
assertTrue(result, "Payment should be authorized");
}
}
This is the earlier post’s code verbatim. It referenced PaymentGateway and OrderService without defining them, so it did not compile on its own. The runnable version with minimal stand-ins is MockitoOrderServiceTest.java and passes on both JUnit 6.1.3 and 5.14.4 (the earlier console output block was not from a captured run and has been dropped; the Surefire result is in the test run, 10 tests, 0 failures). More Mockito: JUnit 6 with Mockito.
Power Through Composition: Multiple Extensions
Stacking extensions allows you to combine heavy lifting like Spring with mock management.
@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
@SpringBootTest
class UserProfileServiceTest {
@Mock
private ExternalService externalService;
@Test
void testWithSpringAndMockito() {
// Test logic
}
}
Code: UserProfileServiceTest.java (the earlier snippet plus imports and a stub interface). Not executed here: it needs a Spring Boot application class. It compiled against spring-test 7.0.10, spring-boot-test 4.1.2, Mockito 5.24.0 and JUnit 6.1.3 (12-spring-snippet-compile.txt). The earlier console output block showed log lines dated 2024 and was not from a run, so it has been dropped.
Redundant, and a trap. As shown in output 10,@SpringBootTestalready registersSpringExtension, so that line can go. Also, a plain@Mockfield is a Mockito mock, not a Spring bean; it will not replace a bean in the Spring context. That second point comes from the Mockito and Spring documentation and was not run here.
Building Your Own Custom Extension
The earlier version of this post had two more extensions. They are kept here, and now they have captured output. The runnable versions write to EventLog instead of System.out; otherwise they are unchanged.
Example 1: Performance Tracker
Using the ExtensionContext.Store ensures your extension is thread-safe and scoped correctly.
public class PerformanceTrackerExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
private static final String START_TIME = "START_TIME";
@Override
public void beforeTestExecution(ExtensionContext context) {
getStore(context).put(START_TIME, System.currentTimeMillis());
}
@Override
public void afterTestExecution(ExtensionContext context) {
long startTime = getStore(context).remove(START_TIME, long.class);
long duration = System.currentTimeMillis() - startTime;
System.out.printf(">>> PERFORMANCE: Test [%s] took %d ms%n", context.getDisplayName(), duration);
}
private ExtensionContext.Store getStore(ExtensionContext context) {
return context.getStore(ExtensionContext.Namespace.create(getClass(), context.getRequiredTestMethod()));
}
}
Runnable version: PerformanceTrackerExtension.java. This one times only the test body (BeforeTestExecutionCallback and AfterTestExecutionCallback), unlike the first extension on this page, which also times @BeforeEach work. Console output when applied to a test that sleeps 42 ms (masked as N):
>>> PERFORMANCE: Test [myTest()] took N ms
Example 2: Database Transaction & Clean-up
In enterprise apps, you often want to wrap tests in a transaction that rolls back automatically to keep the DB clean.
public class TransactionalExtension implements BeforeEachCallback, AfterEachCallback {
@Override
public void beforeEach(ExtensionContext context) {
System.out.println(">>> DB: Starting Transaction for " + context.getDisplayName());
// Logic to begin DB transaction
}
@Override
public void afterEach(ExtensionContext context) {
System.out.println(">>> DB: Rolling back Transaction for " + context.getDisplayName());
// Logic to rollback DB transaction
}
}
Usage & Output:
@ExtendWith(TransactionalExtension.class)
class UserRepositoryTest {
@Test
void testUserSave() {
System.out.println("Executing: Saving User to DB");
}
}
The begin and rollback calls were comments in the earlier post and still are. Runnable versions: TransactionalExtension.java, OriginalExamplesFixture.java. Console output:
>>> DB: Starting Transaction for testUserSave()
Executing: Saving User to DB
>>> DB: Rolling back Transaction for testUserSave()
Transcript: 08-original-examples.txt. For a real transaction, Spring’s own test support does this already.
Advanced: Programmatic Registration with @RegisterExtension
@RegisterExtension is used when you need to pass dynamic data to an extension that can’t be handled via class-level annotations.
class FileSystemTest {
@RegisterExtension
static TempDirectoryExtension tempDir = new TempDirectoryExtension("/custom/path/logs");
@Test
void testLogCreation() {
System.out.println("Using directory: " + tempDir.getPath());
}
}
Runnable version (class renamed RegisterExtensionFixture): RegisterExtensionFixture.java. Console output:
>>> EXTENSION: Initializing directory at /custom/path/logs
Using directory: /custom/path/logs
>>> EXTENSION: Cleaning up directory at /custom/path/logs
JUnit 5 vs JUnit 6: what changed for extension authors
The extension model itself did not change shape. The same extension classes from this page, compiled with --release 17 against both versions, gave the same 14 class files, and the 8 transcripts from mvn test and mvn -Pjunit5 test are byte-for-byte identical (11-junit5-diff.txt).
diff -r output output/junit5 (files 01-08; JUnit 6.1.3 on the left, JUnit 5.14.4 on the right)
no differences: all 8 transcripts are byte-for-byte identical
What did change is in the release notes and in the jars. The first three rows below were checked with javap and javac (09-junit5-vs-6.txt); the rest come from the JUnit 6.1.3 release notes and were not executed here.
| Change in 6.x | Evidence |
|---|---|
Java 17 is the minimum: ExtendWith.class is class-file major 61 in 6.1.3, 52 in 5.14.4 | javap, output 09 |
Store.getOrComputeIfAbsent(...) deprecated; computeIfAbsent(...) added (does not exist in 5.14.4) | javac with -Xlint:deprecation, output 09 |
InvocationInterceptor.interceptDynamicTest(Invocation, ExtensionContext) removed; the three-argument form remains | javap, output 09 |
JSpecify nullability annotations on all modules; JUnit 4 Vintage engine and junit-jupiter-migrationsupport deprecated; junit-platform-runner removed | release notes 6.0.0 |
6.1.0 (19 May 2026) adds @DefaultLocale, @DefaultTimeZone and a system-property extension, moved in from JUnit Pioneer | release notes 6.1.0 |
| Releases 6.1.1 to 6.1.3: no extension API changes | release notes |
The practical advice: write extensions against the 5.x-compatible methods (put, get, remove) if you publish a library that must run on both lines, and use computeIfAbsent only in code that targets 6.x. Output 09 shows the deprecation warning and the compile error:
Excerpt of 09-junit5-vs-6.txt:
junit-jupiter-api 5.14.4: major version: 52
junit-jupiter-api 6.1.3: major version: 61
StoreProbe.java:5: warning: [deprecation] <K,V>getOrComputeIfAbsent(K,Function<? super K,? extends V>) in Store has been deprecated
1 warning
target/probe/src/ComputeProbe.java:5: error: cannot find symbol
JUnit 5.14.4: 14 class files, javac exit status 0
JUnit 6.1.3: 14 class files, javac exit status 0
Migrating? The full list of removals is in the JUnit 5 to JUnit 6 migration guide and JUnit 6 vs JUnit 5. Only the extension-related items are repeated here.
Should you write your own extension?
Usually no, at first. If the behaviour is “do X before each test”, a @BeforeEach method is simpler and easier to read. Reach for an extension when the same logic repeats across many classes, when you need to inject parameters, intercept exceptions, or when a library (Mockito, Spring, Testcontainers) already ships one. Everything on this page also works inside a single class first; extract it only when the second class needs it.
Conclusion: Your Learning Journey
- Start Simple: Use
MockitoExtensionto eliminate setup boilerplate. - Combine Forces: Use multiple
@ExtendWithdeclarations for integration tests. - Go Programmatic: Use
@RegisterExtensionfor dynamic configurations. - Innovate: Build custom extensions for shared concerns like Security Context Injection, Database Clean-up, or API Logging.
Editorial note for the site owner (remove before publishing). This post now overlaps JUnit 6 Extensions Model: both build a timing logger, aParameterResolverand aTestExecutionExceptionHandler. Recommendation for the audit plan: keep this post (it has the ranking history and the@ExtendWithintent) and mergejunit-6-extensionsinto it with a 301 redirect, moving that post’s extension-interface reference into an accordion here. Keep advanced-extensions-junit-6 separate: its retry, soft-assertion andTestTemplatepatterns are different search intent. No post was merged or deleted.
No Comments yet!