Sub topic 15
Extending JUnit with @ExtendWith
JUnit 5 can do a lot on its own. Sometimes, though, you want extra behavior around your tests. You might want to create mocks automatically, time each test, or hand a ready-made object to a test method. JUnit lets you add this kind of behavior with extensions.
An extension is a class that JUnit calls at certain moments while it runs your tests. You attach an extension to a test class or test method with the @ExtendWith annotation.
You have already used one extension in this tutorial. In the chapter on mocks, @ExtendWith(MockitoExtension.class) told JUnit to let Mockito create the @Mock fields. This chapter explains what happened there and shows you how to write simple extensions of your own.
Why Extensions Exist
Without extensions, you would put shared behavior in @BeforeEach and @AfterEach methods. That works inside one test class. When ten test classes need the same setup, you end up copying the same code ten times.
An extension packages that behavior once. Any test class can then use it with one annotation line.
| Approach | Where the code lives | Reuse across classes |
|---|---|---|
| `@BeforeEach` / `@AfterEach` | Inside each test class | Copy and paste |
| Extension with `@ExtendWith` | In its own class | One annotation per test class |
How JUnit Calls an Extension
JUnit runs each test in a fixed series of steps. At each step, JUnit checks for registered extensions that care about that step. If it finds one, it calls the extension's matching method.
The places where an extension can hook in are called extension points. Each extension point is a Java interface. Your extension implements the interfaces for the moments it cares about.
Here are the extension points you will meet most often:
| Interface | When JUnit calls it |
|---|---|
| `BeforeAllCallback` | Once, before all tests in the class |
| `BeforeEachCallback` | Before each test, before `@BeforeEach` methods |
| `BeforeTestExecutionCallback` | Right before the test method itself |
| `AfterTestExecutionCallback` | Right after the test method itself |
| `AfterEachCallback` | After each test, after `@AfterEach` methods |
| `AfterAllCallback` | Once, after all tests in the class |
| `ParameterResolver` | When a test method has parameters to fill in |
| `TestExecutionExceptionHandler` | When a test throws an exception |
Each callback method receives an ExtensionContext. The context is an object that describes the current test: its class, its method, its display name, and more.
Using a Ready-Made Extension: Mockito
Many libraries ship their own JUnit extension. Mockito is the most common one. To use it, add the mockito-junit-jupiter dependency next to JUnit:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.14.2</version>
<scope>test</scope>
</dependency>Then put @ExtendWith(MockitoExtension.class) on the test class:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
interface PriceRepository {
int priceOf(String product);
}
@ExtendWith(MockitoExtension.class)
class PriceRepositoryTest {
@Mock
PriceRepository prices;
@Test
void mockReturnsStubbedPrice() {
when(prices.priceOf("pear")).thenReturn(7);
assertEquals(7, prices.priceOf("pear"));
}
}Before each test, MockitoExtension finds every field marked @Mock and fills it with a fresh mock. After each test, it checks that you did not set up stubs you never used. It reports those as errors, which helps you keep tests tidy.
Writing Your Own Extension: Timing Tests
Now you will write an extension that prints how long each test took. It needs two moments: just before the test runs and just after. That means it implements BeforeTestExecutionCallback and AfterTestExecutionCallback.
The extension must remember the start time between the two calls. JUnit gives each test a store for this. A store is a small key-value box tied to the current test. You pick a namespace, which is a label that keeps your keys apart from other extensions' keys.
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
public class TimingExtension
implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
private static final ExtensionContext.Namespace NAMESPACE =
ExtensionContext.Namespace.create(TimingExtension.class);
@Override
public void beforeTestExecution(ExtensionContext context) {
context.getStore(NAMESPACE).put("start", System.nanoTime());
}
@Override
public void afterTestExecution(ExtensionContext context) {
long start = context.getStore(NAMESPACE).remove("start", long.class);
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println(
context.getRequiredTestMethod().getName() + " took " + millis + " ms");
}
}Use it like any other extension:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(TimingExtension.class)
class TimedCalculatorTest {
@Test
void addIsQuick() {
assertEquals(5, new Calculator().add(2, 3));
}
@Test
void slowTest() throws InterruptedException {
Thread.sleep(50);
assertEquals(2, new Calculator().divide(10, 5));
}
}When you run this class, the output shows lines like addIsQuick took 0 ms and slowTest took 50 ms.
Writing a Parameter Resolver
A test method can take parameters, such as void addWorks(Calculator calculator). JUnit needs someone to supply the value. A ParameterResolver does that job. It has two methods:
supportsParameteranswers "can you supply this parameter?"resolveParameterreturns the actual value.
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;
public class CalculatorParameterResolver implements ParameterResolver {
@Override
public boolean supportsParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) {
return parameterContext.getParameter().getType() == Calculator.class;
}
@Override
public Object resolveParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) {
return new Calculator();
}
}Now any test in the class can ask for a Calculator:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(CalculatorParameterResolver.class)
class InjectedCalculatorTest {
@Test
void addWorks(Calculator calculator) {
assertEquals(5, calculator.add(2, 3));
}
}Each test gets a brand-new Calculator, so tests stay independent.
JUnit itself uses parameter resolvers. That is why you can write void myTest(TestInfo info) or void myTest(TestReporter reporter) without any @ExtendWith. Those resolvers are built in.
Where You Can Put @ExtendWith
You can place @ExtendWith at different levels:
- On the class. The extension applies to every test in the class, including tests in
@Nestedinner classes. - On a method. The extension applies only to that one test.
- On a parent class. Subclasses inherit the extension.
You can also register more than one extension:
@ExtendWith({TimingExtension.class, CalculatorParameterResolver.class})
class BothExtensionsTest {
// tests here
}JUnit registers extensions in the order you list them. "Before" callbacks run in that order. "After" callbacks run in reverse order, so the first extension wraps all the others.
Configuring an Extension with @RegisterExtension
@ExtendWith creates the extension with its no-argument constructor. You cannot pass settings to it. If you need settings, create the extension yourself in a field and mark the field @RegisterExtension:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
class RegisteredTimingTest {
@RegisterExtension
static TimingExtension timing = new TimingExtension();
@Test
void runsWithTiming() {
// TimingExtension prints this test's duration
}
}A static field registers the extension for the whole class, so class-level callbacks such as BeforeAllCallback also work. A non-static field registers it only after the test instance exists.
Common Problems
| Symptom | Likely cause |
|---|---|
| `@Mock` field is `null` | Missing `@ExtendWith(MockitoExtension.class)` |
| `ParameterResolutionException: No ParameterResolver registered` | A test parameter has no extension that supports its type |
| `ParameterResolutionException` about competing resolvers | Two extensions both say they support the same parameter |
| Callback never runs | The extension does not implement the interface for that moment |
| `@RegisterExtension` field ignored | The field is `private` or `null` |
Exercises
Exercise
Your test class has a field @Mock PriceRepository prices; and a test that calls prices.priceOf("apple"). The test fails with a NullPointerException on that line. What is the most likely fix?
Show answer
Add @ExtendWith(MockitoExtension.class) to the test class (and make sure the mockito-junit-jupiter dependency is on the test classpath). Without the extension, nothing creates the mock, so the field stays null.
Exercise
Write an extension named GreetingExtension that prints "Starting: " followed by the test method name before each test. Which interface should it implement, and what does the method look like?
Show answer
Implement BeforeEachCallback. For example: public class GreetingExtension implements BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) { System.out.println("Starting: " + context.getRequiredTestMethod().getName()); } }. Then annotate a test class with @ExtendWith(GreetingExtension.class).
Exercise
A test method is declared as void totalIsCorrect(Calculator calculator), but the class has no extensions. What happens when you run it, and how do you fix it?
Show answer
JUnit throws a ParameterResolutionException because no ParameterResolver supports the Calculator type. Fix it by registering a resolver such as @ExtendWith(CalculatorParameterResolver.class) on the class or method.
Exercise
You register @ExtendWith({A.class, B.class}), and both A and B implement BeforeEachCallback and AfterEachCallback. In what order do their callbacks run?
Show answer
A.beforeEach, then B.beforeEach, then the test, then B.afterEach, then A.afterEach. Before callbacks follow the declared order, and after callbacks run in reverse.