Skip to content
javahacks.dev
JUnit

How to Use JUnit ParameterResolver and Lifecycle Callbacks

Inject your own objects into JUnit 5 test methods and constructors with ParameterResolver, and combine it with lifecycle callbacks to manage resources.

6 min read
Summarize in AI
Flat illustration of a JUnit test run with one failing test, with the JUnit5, GitHub Actions, Cucumber and Selenium logos.

By default JUnit 5 allows test methods to have parameters, but it must be told where the values come from. A ParameterResolver is that source. This builds on the model in writing an extension and runs on JUnit Jupiter 6 and JDK 25.

What is built in

java
@Test
void showsMetadata(TestInfo info, TestReporter reporter) {
    reporter.publishEntry("name", info.getDisplayName());
}

TestInfo, TestReporter and, in repeated tests, RepetitionInfo come from JUnit itself. Anything else needs a resolver, or it fails with a message that no ParameterResolver is registered for the parameter.

A resolver for a temporary database

src/test/java/com/example/DatabaseExtension.javajava
public class DatabaseExtension implements ParameterResolver {

    private static final Namespace NS = Namespace.create(DatabaseExtension.class);

    @Override
    public boolean supportsParameter(ParameterContext p, ExtensionContext ctx) {
        return p.getParameter().getType() == DataSource.class;
    }

    @Override
    public Object resolveParameter(ParameterContext p, ExtensionContext ctx) {
        return ctx.getStore(NS).getOrComputeIfAbsent(
                "ds", key -> new ManagedDataSource(), ManagedDataSource.class).dataSource();
    }

    static class ManagedDataSource implements ExtensionContext.Store.CloseableResource {
        private final DataSource ds = H2.create();
        DataSource dataSource() { return ds; }
        @Override public void close() { H2.shutdown(ds); }
    }
}
java
@ExtendWith(DatabaseExtension.class)
class RepositoryTest {
    @Test
    void savesRows(DataSource ds) throws Exception { /* use ds */ }
}

Storing a CloseableResource means JUnit closes it when the context ends, so no AfterEachCallback is needed for cleanup. Put it in the method context for one database per test, or the class context to share one across the class.

Combining with callbacks

When the resource needs an explicit step, add a callback:

java
public class SeedExtension implements BeforeEachCallback, ParameterResolver {
    @Override public void beforeEach(ExtensionContext ctx) {
        ctx.getStore(NS).put("rows", seed());
    }
    @Override public boolean supportsParameter(ParameterContext p, ExtensionContext c) {
        return p.getParameter().getType() == SeedData.class;
    }
    @Override public Object resolveParameter(ParameterContext p, ExtensionContext c) {
        return c.getStore(NS).get("rows");
    }
}

Constructor injection

Resolvers work for constructor parameters too, so a test class can declare RepositoryTest(DataSource ds) and keep fields final. With the default per-method instance lifecycle, a new instance and new arguments appear for each test.

Qualifying by annotation

When several values share a type, claim by annotation:

java
@Retention(RUNTIME) @Target(PARAMETER) @interface Tenant { String value(); }

public boolean supportsParameter(ParameterContext p, ExtensionContext ctx) {
    return p.isAnnotated(Tenant.class);
}

Parameterised tests use the same mechanism, so a resolver and @ParameterizedTest can supply different parameters, as described in parameterized tests.

Failure modes to expect

Two resolvers claiming the same parameter type give a ParameterResolutionException that names both classes, so keep supportsParameter narrow and prefer a marker annotation over a broad type like String. A resolver that returns the wrong type fails at invocation with a message about an argument mismatch. If the value is expensive, create it in the class context so it is built once, and make sure it is thread safe when parallel execution is on. Cleanup that runs after a test fails is the main reason to prefer CloseableResource over a callback you might forget to wire.

Finally, remember that resolution happens before the test body. An exception thrown in resolveParameter is reported as a test failure with the resolver in the stack, which makes setup errors easy to find.

The extension store, and why it matters

An extension must not keep state in its own fields, because one instance serves many tests, possibly at the same time. State goes in the ExtensionContext.Store, which is scoped to a test, a class or the whole run depending on the namespace and the context you ask for. Getting an entry with getOrComputeIfAbsent creates it once per scope, and if the value implements AutoCloseable through CloseableResource, JUnit closes it when the scope ends. That is how a resolver that starts a database for a class cleans it up without an @AfterAll method written by every user of the extension.

java
Connection db = context.getRoot()
        .getStore(NAMESPACE)
        .getOrComputeIfAbsent("db", k -> new CloseableConnection(open()), CloseableConnection.class)
        .connection();

Choose the context deliberately. The method-level store gives each test its own value and drops it afterwards, and the root store gives one for the whole run, shared by every test. A database container belongs at the root, since starting one per test would take minutes. A transaction belongs to the method.

Registering declaratively and programmatically

@ExtendWith(MyExtension.class) is the simple way, and the extension is created by JUnit with a no-argument constructor. When the extension needs configuration, use a field annotated @RegisterExtension, which you construct yourself, and give it a builder or constructor arguments. A static field of that kind also takes part in the class-level callbacks, and an instance field does not. If two extensions depend on each other's order, register them as fields and set @Order on them, and the order is stated in the code and not left to chance.

Resolving a parameter by type and annotation

supportsParameter should be strict and cheap. Match on the exact type, and on an annotation if you want a qualifier, so that your resolver does not claim a parameter that belongs to another extension. If two resolvers both claim one, JUnit fails with ParameterResolutionException: Discovered multiple competing ParameterResolvers, and the message names both, so the fix is to narrow one of them. When no resolver claims a parameter, the message says No ParameterResolver registered for parameter, which usually means the extension is not registered on the class.

Failure modes in callbacks

An exception in beforeEach fails the test and still runs the matching afterEach callbacks of the extensions that had already started, so write afterEach to tolerate a missing resource. An exception in afterEach is reported in addition to a test failure, and hides nothing, but it does make a report with two errors to read. Log the cleanup failures and keep going where you can, so that one failed close does not leave the next resource open.

Thread safety under parallel execution

If the suite runs in parallel, an extension is called from several threads at once. Keep it stateless apart from the store, use a namespace that includes the test's unique id when state is per test, and avoid static mutable fields. A resolver that hands every test the same connection object works in a sequential run and corrupts data in a parallel one. A short parallel run of the extension's own tests is the way to prove it.

A small example, end to end

A suite needs a unique schema per test class. An extension implements BeforeAllCallback to create the schema, ParameterResolver to hand the connection to tests that ask for it, and AfterAllCallback to drop the schema, and tests declare Connection db as a parameter. The tests contain no setup and no cleanup, and the extension is written once and reused in every module. That is the payoff of the extension model: the knowledge of how to prepare a resource lives in one class and not in forty @BeforeEach methods.

Where to keep extensions

Put shared extensions in a small test-support module, published as a test-jar or a normal artifact with test scope, with its own unit tests, and keep the project-specific ones next to the tests that use them. Document each extension's purpose and scope in a Javadoc comment, since a test annotated with an extension nobody remembers is a mystery to the next reader.

Where this does not apply

For one off construction, a helper method in the test class is clearer. Use a resolver when many classes need the same managed object. The behaviour is specified in the ParameterResolver Javadoc and the user guide on parameter resolution.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.