Sub topic 15
Extending JUnit with @ExtendWith
What an extension is
An extension is a class that adds extra behavior to JUnit. JUnit calls the extension at set moments while your tests run, such as before each test or after each test.
You turn on an extension with the @ExtendWith annotation. You can put it on a test class or on a single test method.
You have already used one. In the chapter on mocks, @ExtendWith(MockitoExtension.class) let Mockito create your @Mock fields. Mockito wrote that extension. You can also write your own.
Why extensions matter
Some setup code repeats across many test classes. Timing tests, logging, and preparing objects are common cases. You could copy @BeforeEach methods into every class, but copies drift apart. An extension keeps that code in one place, and any test class can reuse it with one line.
How JUnit calls an extension
An extension point is a moment in the test lifecycle where JUnit checks for extensions. Each point is a Java interface. Your extension implements the interfaces for the moments it cares about.
| Interface | When JUnit calls it |
|---|---|
| `BeforeAllCallback` | Once, before all tests in the class |
| `BeforeEachCallback` | Before each test method |
| `AfterEachCallback` | After each test method |
| `AfterAllCallback` | Once, after all tests in the class |
| `ParameterResolver` | When a test method has a parameter to fill in |
Writing a timing extension
This extension measures how long each test takes. It saves the start time in a store, which is a small map that JUnit keeps for each test. The namespace is a label that stops your keys from clashing with keys from other extensions.
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
public class TimingExtension implements BeforeEachCallback, AfterEachCallback {
private static final ExtensionContext.Namespace NAMESPACE =
ExtensionContext.Namespace.create(TimingExtension.class);
@Override
public void beforeEach(ExtensionContext context) {
context.getStore(NAMESPACE).put("start", System.nanoTime());
}
@Override
public void afterEach(ExtensionContext context) {
long start = context.getStore(NAMESPACE).get("start", Long.class);
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println(context.getDisplayName() + " took " + millis + " ms");
}
}The ExtensionContext gives the extension details about the current test, such as its display name.
Using the extension
Add @ExtendWith to the test class. Every test in the class is now timed.
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 {
private final Calculator calculator = new Calculator();
@Test
void addReturnsSum() {
assertEquals(5, calculator.add(2, 3));
}
@Test
void divideReturnsQuotient() {
assertEquals(4, calculator.divide(8, 2));
}
}When you run it, the output shows a line such as addReturnsSum() took 0 ms for each test.
You can turn on more than one extension at once:
@ExtendWith({MockitoExtension.class, TimingExtension.class})
class CheckoutServiceTimedTest {
// tests here
}Exercises
Exercise
Which interface must an extension implement to run code after every test method?
Show answer
AfterEachCallback. JUnit calls its afterEach(ExtensionContext) method after each test method finishes.
Exercise
Why does TimingExtension use a namespace when it saves the start time in the store?
Show answer
The namespace keeps its "start" key separate from keys that other extensions save, so two extensions cannot overwrite each other's values.
Exercise
You want TimingExtension to time only one test method, not the whole class. Where do you put @ExtendWith(TimingExtension.class)?
Show answer
Put it on that single test method instead of on the class. JUnit then applies the extension only to that method.