Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 29 ยท JUnit advanced

Writing JUnit Extensions

Learn the JUnit Jupiter extension model. Write lifecycle callbacks, a ParameterResolver and a TestWatcher, use @RegisterExtension and @TempDir, and replace JUnit 4 rules.

Sooner or later every test suite needs the same helper in many places: start a fake clock, open a database transaction, create a temporary folder, log which tests failed. In the first JUnit versions you did this with inheritance (a shared base class) or with special runners. Both approaches break down quickly, because a class can extend only one parent and can use only one runner.

JUnit Jupiter (the API of JUnit 5 and 6) replaced all of that with one idea: the extension model. An extension is a small class that implements one or more callback interfaces. You attach it to a test class or method, and JUnit calls it at the right moments. Because you can attach as many extensions as you like, they compose in a way that base classes never could. Most of what you use daily, including @TempDir, @ParameterizedTest and Mockito's @ExtendWith(MockitoExtension.class), is built on it.

This lesson uses the real JUnit library on our Java runner. If you need the lifecycle annotations first, read Lifecycle, Nested Tests and Display Names.

One idea, many hooks

Extension A class that plugs into the test run.
Callbacks JUnit calls you before and after things.
Resolvers JUnit asks you for parameter values.

Attach as many extensions as you need.

1 / 3

What an extension looks like

An extension is any class that implements org.junit.jupiter.api.extension.Extension through one of its sub-interfaces. You pick the interfaces for the moments you care about, and implement only those methods:

Interface Called
BeforeAllCallback, AfterAllCallback once around the whole class
BeforeEachCallback, AfterEachCallback around every test method
BeforeTestExecutionCallback, AfterTestExecutionCallback tightly around the test body only (good for timing)
ParameterResolver when a method needs a value for a parameter
TestInstancePostProcessor right after JUnit creates the test object
ExecutionCondition to enable or disable a test (this powers @EnabledOnOs)
TestWatcher after a test finishes: success, failure, abort or disabled
TestExecutionExceptionHandler when a test throws, to rethrow, translate or swallow it

Every callback receives an ExtensionContext. It tells you which class, method and display name you are working on, and it carries a Store, a key-value area scoped to the current class or method, where an extension keeps its state between callbacks. Never keep per-test state in a field of the extension itself: JUnit creates one extension object and may share it between tests.

Attach extensions with @ExtendWith({A.class, B.class}) on a test class, method, or even a parameter. JUnit instantiates the classes with their public no-argument constructors and calls them in registration order for "before" callbacks, and in reverse order for "after" callbacks, like nested try/finally blocks.

Lifecycle callbacks, a resolver and a watcher

Below, one test class uses three extensions. The first records every callback into a list so you can see the exact order. The second, a ParameterResolver, hands a User object to any test method that declares a User parameter. The third, a TestWatcher, logs how each test ended. One test fails and one is disabled on purpose.

Java Callbacks, ParameterResolver and TestWatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the log from top to bottom. beforeAll happens once, then each test is wrapped by beforeEach and afterEach, and the watcher speaks last for each test, after the afterEach callback. The disabled test never reaches beforeEach, but the watcher still hears about it. Notice that the test methods contain no setup code and no object creation: the extension delivered the User.

Parameters: how resolution really works

supportsParameter is asked for every parameter of every test and lifecycle method, so keep it cheap and specific (check the type, or a custom annotation on the parameter). JUnit already has resolvers for TestInfo, TestReporter, RepetitionInfo and @TempDir paths. If two resolvers claim the same parameter, JUnit fails the test with a "competing resolvers" error rather than guessing, so make yours specific.

@RegisterExtension: extensions with configuration

@ExtendWith only takes a class, so JUnit creates the instance and you cannot pass arguments. When an extension needs configuration, or the test must call methods on it, declare it as a field and annotate it with @RegisterExtension. A static field is registered for the whole class (and can implement BeforeAllCallback); an instance field is registered per test.

The next program uses a FakeClock extension. The test reads the extension's current time directly, advances it, and the extension resets it before each test. It also shows the built-in @TempDir, which hands the test a fresh, empty directory and deletes it afterward.

Java @RegisterExtension and @TempDir

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

All four pass, whichever order JUnit runs them in. Test three would fail if the extension did not reset the clock, because the second test advances it by thirty minutes. This is the pattern: an extension owns the state and the cleanup, so tests cannot forget.

Replacing JUnit 4 runners and rules

JUnit 4 had two extension mechanisms, and both map directly onto the one model:

JUnit 4 JUnit Jupiter
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class) (included in Spring's test annotations)
@Rule TemporaryFolder @TempDir Path dir
@Rule ExpectedException assertThrows(...)
@Rule TestName a TestInfo parameter
@Rule / @ClassRule with your own rule a class implementing BeforeEachCallback and AfterEachCallback (or BeforeAllCallback / AfterAllCallback)
@Rule Timeout @Timeout

A JUnit 4 runner could only be chosen once per class; extensions stack. See Migrating from JUnit 4 and Between Frameworks for the full path.

Good habits

  • Keep state in the Store, not in extension fields, unless the extension is deliberately a per-class singleton like the clock above.
  • Fail loudly. If the extension cannot do its job, throw an exception with a clear message; a silently skipped setup produces confusing test failures later.
  • Prefer a built-in (@TempDir, @Timeout, @EnabledOnOs) when one exists, and write your own only for logic that belongs to your project.
  • Register project-wide extensions once. Setting junit.jupiter.extensions.autodetection.enabled=true lets JUnit load extensions listed in META-INF/services/org.junit.jupiter.api.extension.Extension, so you do not repeat @ExtendWith on every class.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a Jupiter test class use several extensions while a JUnit 4 class could use only one runner?

    An extension implements only the callbacks it needs, and JUnit calls every registered extension in order. A runner took over the entire execution of the class, so only one could be active.
  2. 2. When do you need @RegisterExtension instead of @ExtendWith?

    @ExtendWith only names a class, which JUnit instantiates with a no-argument constructor. A @RegisterExtension field lets you construct and configure the object yourself and use it from the test.
  3. 3. A test method has the parameter Customer c, and no resolver supports it. What happens?

    Parameters of test methods are never filled in silently. JUnit fails with a ParameterResolutionException unless a registered ParameterResolver supports the parameter.
  4. 4. Which JUnit 4 feature does @TempDir Path dir replace?

    @TempDir injects a fresh temporary directory and deletes it after the test, which is exactly what the TemporaryFolder rule did.

Summary

  • An extension is a class implementing Jupiter callback interfaces; it composes with other extensions, unlike runners and base classes.
  • Callbacks run in registration order before and in reverse order after. ExtensionContext gives names and a Store for per-test state.
  • ParameterResolver injects values into test methods; TestWatcher reports each test's outcome; ExecutionCondition decides whether tests run.
  • @ExtendWith attaches a class declaratively; @RegisterExtension attaches a configured instance held in a field.
  • @TempDir gives each test a fresh directory; rules and runners from JUnit 4 all have extension equivalents.

Next: Testing Exceptions, Timeouts and Async Code.