Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 29 ยท Comparing and migrating

Migrating from JUnit 4 and Between Frameworks

Move from JUnit 4 to Jupiter with the Vintage engine, map annotations and rules to extensions, convert between JUnit and TestNG, and migrate step by step.

Test code lives for a decade. Many projects still carry thousands of JUnit 4 tests, and some teams want to move to TestNG or back. A migration is a refactoring: behavior must stay the same while the tools change, so the key skill is doing it in small, safe steps with the tests running at every step.

This lesson shows how to move from JUnit 4 to Jupiter (the JUnit 5/6 API) using the Vintage engine to run both side by side, which annotations map to which, how rules become extensions, how to convert between JUnit and TestNG, and a strategy that avoids a risky big-bang rewrite. Read JUnit vs TestNG: Choosing Between Them first if you are unsure whether to migrate at all.

Real versus stand-in. Java and build configuration in code blocks is real and read-only; the site cannot run JUnit 4 or TestNG here. The TryIt blocks are JavaScript stand-ins: a small annotation mapper and an assertion-argument converter. They show the idea behind migration tools such as OpenRewrite, but they handle only simple, regular code. Always review real tool output.

A safe migration in four moves

Run both Vintage engine runs old tests beside new ones.
Convert gradually One package or class at a time.
Replace rules Turn rules into extensions.
Remove Vintage When no JUnit 4 test is left.

Keep the build green after every step.

1 / 2

Why the Platform makes it easy

JUnit 5 and 6 split the project into the JUnit Platform (discovers and runs tests), Jupiter (the new programming model) and Vintage (an engine that runs JUnit 3 and 4 tests). Because the Platform can load several engines at once, an old and a new test can sit in the same module and run in the same build. This is what makes gradual migration possible: you never need to convert everything before the build works.

JUnit 6 keeps this design. Jupiter tests written for JUnit 5 almost always compile unchanged, and the Vintage engine still exists for old tests but is deprecated, so treat it as a bridge and not a destination. Check the release notes of the exact JUnit version you use before you start.

Step 1: add Jupiter and Vintage next to JUnit 4

Keep your existing JUnit 4 dependency and add the BOM, Jupiter and the Vintage engine, then switch the build to the Platform:

XML
<dependencies>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
  </dependency>
</dependencies>

Run the build. All old tests must still pass, now executed by Vintage. Do not convert anything in this step; the goal is a green build with both engines.

Step 2: convert test classes

Convert one class or package at a time, run the tests, and commit. The mapping is mostly mechanical:

JUnit 4 Jupiter (JUnit 5/6)
org.junit.Test org.junit.jupiter.api.Test
@Before / @After @BeforeEach / @AfterEach
@BeforeClass / @AfterClass @BeforeAll / @AfterAll (static unless @TestInstance(PER_CLASS))
@Ignore @Disabled
@Category @Tag
@Test(expected = X.class) assertThrows(X.class, () -> ...)
@Test(timeout = 500) @Timeout(value = 500, unit = MILLISECONDS)
@RunWith(...) @ExtendWith(...)
@Rule / @ClassRule extension, @RegisterExtension or @TempDir
org.junit.Assert org.junit.jupiter.api.Assertions
org.junit.Assume org.junit.jupiter.api.Assumptions
@Parameterized runner @ParameterizedTest with sources

Test classes and methods can be package-private in Jupiter; public is no longer needed. Keep a class either entirely JUnit 4 or entirely Jupiter, because mixing annotations in one class does nothing useful: the engine that discovers it only reads its own annotations.

A mapper in miniature

The first stand-in converts imports and annotations with plain text rules, and lists what needs a human. It is the same idea, much simplified, as a recipe in a refactoring tool. Notice what it refuses to guess: expected= and @Rule.

JS Map JUnit 4 annotations to Jupiter

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

No output.

Look at the output: the simple renames are done, but @Ignore became @Disabled without its import (this sample never imported org.junit.Ignore, a tiny reminder that text rules do not understand code). A real tool works on the syntax tree and fixes imports too. The expected= and @Rule lines are listed for a human, which is the correct behavior.

Watch the assertion argument order

Jupiter moved the optional message to the last argument: assertEquals(expected, actual, "message"). JUnit 4 had it first. If you only rename the import, an old call assertEquals("sum", 5, add(2, 3)) still compiles in some overloads and then fails in strange ways. Convert assertions carefully, or use a tool that handles them. TestNG goes further: assertEquals(actual, expected, message) swaps the first two arguments too.

JS Convert assertion arguments

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

No output.

The converter has a built-in weakness that is worth remembering: when an assertion compares two Strings, assertEquals("a", "b", "c") cannot be told apart from "message, expected, actual" by looking at the code. Tools guess; humans must review. In practice, compile errors and running the tests are your safety net.

Step 3: replace runners and rules with extensions

Runners (@RunWith) and rules (@Rule, @ClassRule) were JUnit 4's extension mechanism. Jupiter replaces both with one model, covered in Writing JUnit Extensions:

  • @RunWith(SpringRunner.class) becomes @ExtendWith(SpringExtension.class) (Spring Boot's @SpringBootTest already includes it).
  • @RunWith(MockitoJUnitRunner.class) becomes @ExtendWith(MockitoExtension.class); see Mocks and Spies with Mockito.
  • TemporaryFolder becomes the @TempDir annotation on a Path or File field or parameter.
  • Custom rules become classes that implement callbacks such as BeforeEachCallback and AfterEachCallback, registered with @ExtendWith or @RegisterExtension.
  • The junit-jupiter-migrationsupport module offers @EnableRuleMigrationSupport for a few built-in rule types (ExternalResource, Verifier, ExpectedException) as a temporary step.

The @RunWith(Parameterized.class) runner has no automatic replacement; rewrite those tests with @ParameterizedTest and a source, after reading Parameterized and Dynamic Tests.

Step 4: remove JUnit 4 and Vintage

When no class imports org.junit.Test any more, remove the junit:junit dependency and the Vintage engine. A search such as grep -r "import org.junit\.[A-Z]" src/test (note the capital letter, which skips org.junit.jupiter) tells you whether you are done. Also look for transitive JUnit 4 uses in helper libraries before deleting the dependency.

Between JUnit and TestNG

Moving between the two frameworks is similar in effort, with these main differences:

  • Instance lifecycle. TestNG shares one instance per class; Jupiter creates one per method. Moving from TestNG to JUnit often fixes hidden order dependencies. Moving the other way can expose that fields now leak between tests.
  • Setup hooks. @BeforeMethod โ†” @BeforeEach, @BeforeClass โ†” @BeforeAll (static in JUnit by default), @BeforeSuite/@BeforeTest have no direct JUnit equivalent: use extensions, a Launcher session listener, or static initialization.
  • Data. @DataProvider โ†” @ParameterizedTest with @MethodSource; @Parameters from XML โ†” system properties or configuration.
  • Groups. @Test(groups = ...) โ†” @Tag; the XML include/exclude moves to build-tool filters.
  • Dependencies. dependsOnMethods has no JUnit counterpart. Rewrite the scenarios so each test creates its own preconditions.
  • Expected exceptions. @Test(expectedExceptions = X.class) โ†” assertThrows.
  • Assertions. Swap argument order as shown above.

A migration strategy that works

  1. Freeze features. Run the whole suite and record the count and time. A migration must not change what is tested.
  2. Make the build green with both engines. Add Jupiter and Vintage (or the TestNG engine) and keep everything passing.
  3. Convert in small batches. One package per pull request. Compare the test count before and after (the numbers must match) and run the suite in CI.
  4. Prefer mechanical tools for the bulk. OpenRewrite has recipes for JUnit 4 to Jupiter; IDEs offer migration refactorings. Review the diff anyway.
  5. Improve afterwards, not during. Do not rewrite test logic in the same change as the migration; it makes failures impossible to explain.
  6. Delete the bridge. Remove Vintage and the old dependency, and add a build rule or lint check that bans the old imports.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Vintage engine do?

    Vintage lets old tests run in the same build as Jupiter tests. It does not change any source code.
  2. 2. Which Jupiter construct replaces @Test(expected = IllegalStateException.class)?

    assertThrows runs a lambda and checks the exception type, and it lets you inspect the exception and assert on code after the call.
  3. 3. Where does the optional message go in Jupiter's assertEquals, compared with JUnit 4?

    JUnit 4 had assertEquals(message, expected, actual); Jupiter uses assertEquals(expected, actual, message).
  4. 4. What replaces the JUnit 4 TemporaryFolder rule?

    @TempDir injects a temporary directory as a Path or File and deletes it after the test.
  5. 5. What is the best way to run a large migration?

    Small steps with a green build and a matching test count make problems easy to find and the change easy to review.

Summary

  • The JUnit Platform runs several engines, so JUnit 4 (Vintage) and Jupiter tests can live in one build.
  • First make the build green with both engines; convert one package at a time; remove Vintage last.
  • Annotations map mostly one to one; expected=, timeouts, rules, runners and @Parameterized need a rewrite.
  • Jupiter puts the assertion message last; TestNG also swaps expected and actual.
  • Rules and runners become extensions; TemporaryFolder becomes @TempDir.
  • Moving between JUnit and TestNG changes instance lifecycle, setup hooks, groups and dependencies.
  • Use tools for the mechanical part, review the diff, and do not mix refactoring with migration.

Next: Mocks and Spies with Mockito.