Skip to content
javahacks.dev
JUnit

Migrate From JUnit 4 Rules to JUnit 5 Extensions Safely

Migrate JUnit 4 rules to JUnit 5 extensions: TemporaryFolder to TempDir, ExpectedException to assertThrows and custom rules to callbacks.

6 min read
Summarize in AI
Flat illustration of a staircase from one version to the next, with the JUnit5, Spring Boot, OpenJDK and Gradle logos.

JUnit 4 had two extension points that overlapped and confused newcomers: runners and rules. JUnit 5 replaces both with one mechanism, extensions. Migrating a rule therefore means one of two things: finding the built-in replacement, which exists for most common rules, or rewriting the rule as an extension. This guide gives the mapping table for the built-in rules, converts a custom rule that manages a resource, covers runners, shows the migration support module and its limits, explains rule ordering and scope, and ends with a safe order of work. Examples use JUnit 5.13 and apply to JUnit 6.

Built-in rules

JUnit 4 ruleJUnit 5 replacement
TemporaryFolder@TempDir
ExpectedExceptionassertThrows
Timeout@Timeout
TestNameTestInfo parameter
ExternalResourceBeforeEachCallback and AfterEachCallback, or @BeforeEach
ErrorCollectorassertAll
VerifierAfterEachCallback

Start with these, because each conversion is small, mechanical and removes a dependency on the old API. Examples of the three most frequent:

java
// JUnit 4
@Rule public TemporaryFolder folder = new TemporaryFolder();

// JUnit 5
@TempDir Path folder;
java
// JUnit 4
@Rule public ExpectedException thrown = ExpectedException.none();
@Test public void fails() { thrown.expect(IllegalStateException.class); service.run(); }

// JUnit 5
@Test void fails() { assertThrows(IllegalStateException.class, () -> service.run()); }
java
// JUnit 4
@Rule public TestName name = new TestName();

// JUnit 5
@BeforeEach void init(TestInfo info) { System.out.println(info.getDisplayName()); }

The ExpectedException conversion is better than a rename. The old rule applied to the whole test and so could pass when the exception came from setup code, while assertThrows wraps exactly one call, which makes the test stricter and the intent clearer. Expect a few tests to fail after conversion because they were passing for the wrong reason, and treat that as a finding.

Custom rule to extension

A rule that starts a resource before each test and stops it afterwards is the most common custom rule:

java
// JUnit 4
public class DatabaseRule extends ExternalResource {

    private Database db;

    protected void before() { db = Database.start(); }

    protected void after() { db.stop(); }

    public Database db() { return db; }
}

The JUnit 5 version implements the callback interfaces it needs.

java
// JUnit 5
public class DatabaseExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver {

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

    @Override
    public void beforeEach(ExtensionContext ctx) {
        ctx.getStore(NS).put("db", Database.start());
    }

    @Override
    public void afterEach(ExtensionContext ctx) {
        ctx.getStore(NS).remove("db", Database.class).stop();
    }

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

    @Override
    public Object resolveParameter(ParameterContext p, ExtensionContext c) {
        return c.getStore(NS).get("db", Database.class);
    }
}
java
@ExtendWith(DatabaseExtension.class)
class OrderRepositoryTest {

    @Test
    void saves(Database db) { /* ... */ }
}

The extension keeps its state in the ExtensionContext store, not in fields, because one extension instance serves all tests and fields would be shared. A parameter resolver lets tests receive the resource directly as a method argument, which is the new capability worth adopting: the test no longer reaches into a rule field. For resources that should live for the whole class, implement BeforeAllCallback and AfterAllCallback, or use a CloseableResource in the root store so the resource is shared and closed once.

Runners

@RunWith(MockitoJUnitRunner.class) becomes @ExtendWith(MockitoExtension.class). Spring's runner is replaced by SpringExtension, which the test slice annotations already include. Custom runners need a rewrite as extensions, or as a test engine if they changed how tests are discovered. The parameterised runner and the suite runners have direct replacements in the platform, as described in JUnit 5 parameterized tests and the suite engine.

The migration support module

XML
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-migrationsupport</artifactId>
  <scope>test</scope>
</dependency>
java
@EnableRuleMigrationSupport
class LegacyTest {

    @Rule public TemporaryFolder folder = new TemporaryFolder();
}

The module supports rules that extend ExternalResource and Verifier, and ExpectedException, so old classes run unchanged on the new engine. It is a transitional aid, and the module is marked experimental. Use it to move a large suite to the JUnit 5 platform in one step, then convert the classes at your own pace, and remove the module when the last rule is gone. Leaving it in place indefinitely keeps a dependency on the JUnit 4 API alive.

Rule ordering and scope

JUnit 4 rules could be ordered with RuleChain and shared across a class with @ClassRule. In JUnit 5 the equivalents are the order of @ExtendWith declarations, which run top to bottom for before-callbacks and in reverse for after-callbacks, and a static field registered with @RegisterExtension for per-class state. When two rules depended on each other, such as a database rule that needs a network rule, keep that order explicit by listing the extensions in the same sequence on the class. Check also whether a rule used a Statement to wrap a test. The closest match is the InvocationInterceptor, which can run code around the test method and handle its exceptions.

Order of work

First replace the built-in rules with the table above. Second convert the custom rules to extensions, starting with the ones most classes use. Third delete the migration support dependency. Fourth remove JUnit 4 entirely, following the full migration. Run the whole suite after each step and compare the test count with the baseline, since a silently skipped test is the main risk of any migration.

Writing the extension well

A few habits make a converted extension dependable. Keep all mutable state in the ExtensionContext store, scoped to the method or the class, because extension instances are shared and may be used by parallel tests. Clean up in the after-callback even when the test failed, and guard against a failure in the before-callback leaving a half-started resource. Use ExtensionContext.Store.CloseableResource for things that close, so JUnit closes them at the right scope, even if your after-callback never runs. Declare the extension with @ExtendWith on the class when every test needs it, and with @RegisterExtension as a field when it needs constructor arguments or must be configured by the test. Write one small test for the extension itself, using the JUnit Platform Test Kit if it has non-trivial behaviour.

Tests that relied on rule side effects

Some rules changed global state in ways tests came to depend on, for instance setting a system property or replacing a static clock. When converting, search for the readers of that state and make the dependency explicit as a parameter or a field. A converted test that still passes because the old rule ran in a neighbouring class is a trap that appears only when tests run in a different order, so run the suite shuffled once after the migration.

Checking the result

After the last rule is converted, search the test sources for org.junit.Rule, org.junit.runner and org.junit.Test. Any hit is a test that still runs on the Vintage engine or not at all. The Vintage engine can be dropped from the build once the search is clean.

Mixing Vintage and Jupiter during the move

The Vintage engine lets old and new tests run in one build, so a project can move class by class. Watch for tests that exist in both worlds with the same name.

When to leave a rule alone

Tests that remain on JUnit 4 keep their rules, and there is no urgency to convert code that works and rarely changes. The architecture behind extensions is explained in JUnit 5 architecture. The references are the extension model and the migration tips of the user guide.

Taggedmigration
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.