JUnit 5 vs JUnit 4: Migration Guide and New Features
JUnit 5 is not a drop-in replacement for JUnit 4. It's a ground-up redesign that ships as three modules, replaces runners and rules with a cleaner extension model, and adds first-class support for parameterized tests, dynamic tests, and nested test classes. This guide covers the key differences and walks you through migrating a real project.
Architecture: One JAR vs Three Modules
JUnit 4 shipped as a single junit-4.x.jar. JUnit 5 ships as:
- JUnit Platform — the launcher, test engine SPI, reporting
- JUnit Jupiter — the new API you write tests against (
@Test,@BeforeEach, etc.) - JUnit Vintage — engine that runs JUnit 4 and JUnit 3 tests on the platform
This separation means you can run JUnit 4 and JUnit 5 tests in the same project during migration using the Vintage engine.
Annotation Changes
| JUnit 4 | JUnit 5 | Notes |
|---|---|---|
@Test |
@Test |
Package changed to org.junit.jupiter.api |
@Before |
@BeforeEach |
|
@After |
@AfterEach |
|
@BeforeClass |
@BeforeAll |
Method no longer needs to be static (with @TestInstance) |
@AfterClass |
@AfterAll |
Same as above |
@Ignore |
@Disabled |
Accepts optional reason string |
@Category |
@Tag |
|
@RunWith |
@ExtendWith |
|
@Rule |
@ExtendWith or field extensions |
|
@ClassRule |
@ExtendWith or static field extensions |
The @Test annotation in JUnit 5 no longer accepts expected or timeout parameters. Those move to assertThrows() and assertTimeout().
Before/After example
JUnit 4:
import org.junit.Before;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
public class OrderServiceTest {
@BeforeClass
public static void setUpClass() {
// runs once before all tests
}
@Before
public void setUp() {
// runs before each test
}
@Test
public void testOrder() {
// test body
}
@After
public void tearDown() {
// runs after each test
}
@AfterClass
public static void tearDownClass() {
// runs once after all tests
}
}JUnit 5:
import org.junit.jupiter.api.*;
class OrderServiceTest {
@BeforeAll
static void setUpClass() {
// runs once before all tests
}
@BeforeEach
void setUp() {
// runs before each test
}
@Test
void testOrder() {
// test body
}
@AfterEach
void tearDown() {
// runs after each test
}
@AfterAll
static void tearDownClass() {
// runs once after all tests
}
}Note: JUnit 5 test classes and methods don't need to be public. Package-private is fine.
Assertions
JUnit 5 ships with org.junit.jupiter.api.Assertions. The API is largely the same but with important additions.
assertThrows replaces @Test(expected = ...)
JUnit 4:
@Test(expected = IllegalArgumentException.class)
public void rejectsNegativeAmount() {
account.withdraw(-100);
}JUnit 5:
@Test
void rejectsNegativeAmount() {
IllegalArgumentException ex = assertThrows(
IllegalArgumentException.class,
() -> account.withdraw(-100)
);
assertEquals("Amount must be positive", ex.getMessage());
}JUnit 5's approach lets you assert on the exception message and cause, not just the type.
assertTimeout replaces @Test(timeout = ...)
JUnit 4:
@Test(timeout = 1000)
public void completesQuickly() {
service.process();
}JUnit 5:
@Test
void completesQuickly() {
assertTimeout(Duration.ofMillis(1000), () -> service.process());
}assertTimeoutPreemptively aborts the test if it exceeds the timeout; assertTimeout waits for completion.
assertAll for grouped assertions
JUnit 5 adds assertAll, which runs all assertions even when some fail:
@Test
void orderFields() {
Order order = service.create("item-1", 3);
assertAll("order",
() -> assertEquals("item-1", order.getItemId()),
() -> assertEquals(3, order.getQuantity()),
() -> assertNotNull(order.getId()),
() -> assertEquals(OrderStatus.PENDING, order.getStatus())
);
}Without assertAll, the first failing assertion stops the test. With it, you see all failures at once.
Assumptions
org.junit.Assume → org.junit.jupiter.api.Assumptions:
@Test
void onlyOnLinux() {
assumeTrue(System.getProperty("os.name").contains("Linux"));
// rest of test only runs on Linux
}Runners vs Extensions
JUnit 4 used @RunWith to plug in test frameworks:
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
@Mock
private Repository repo;
}JUnit 5 uses @ExtendWith:
@ExtendWith(MockitoExtension.class)
class ServiceTest {
@Mock
private Repository repo;
}Extensions can do everything runners could, plus more: inject parameters, intercept lifecycle, post-process instances. Multiple extensions compose naturally:
@ExtendWith({MockitoExtension.class, SpringExtension.class})
class ServiceTest { ... }Rules vs Extensions
JUnit 4 @Rule and @ClassRule had no JUnit 5 equivalent initially, but the junit-vintage-engine and migration support added @EnableRuleMigrationSupport (from junit-jupiter-migrationsupport) to run select JUnit 4 rules:
@EnableRuleMigrationSupport
class LegacyTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
}For new code, replace rules with extensions or JUnit 5 built-ins like @TempDir.
@TempDir replaces TemporaryFolder
JUnit 4:
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void writesFile() throws IOException {
File file = tempFolder.newFile("output.txt");
}JUnit 5:
@Test
void writesFile(@TempDir Path tempDir) throws IOException {
Path file = tempDir.resolve("output.txt");
Files.writeString(file, "content");
}Parameterized Tests
JUnit 4 required the Parameterized runner and a specific static factory method pattern. JUnit 5 makes parameterized tests first-class:
@ParameterizedTest
@ValueSource(strings = {"", " ", "\t"})
void rejectsBlankInput(String input) {
assertThrows(IllegalArgumentException.class, () -> service.process(input));
}
@ParameterizedTest
@CsvSource({
"USD, 100, 100.00",
"EUR, 150, 150.00",
"GBP, 200, 200.00"
})
void formatsAmount(String currency, int amount, String expected) {
assertEquals(expected, formatter.format(currency, amount));
}See the dedicated JUnit 5 parameterized tests guide for the full API.
Nested Tests
JUnit 5 adds @Nested for organizing related tests in inner classes:
class AccountTest {
@Nested
class WhenEmpty {
@Test
void balanceIsZero() { ... }
@Test
void withdrawThrows() { ... }
}
@Nested
class WhenFunded {
@BeforeEach
void deposit() { account.deposit(500); }
@Test
void canWithdraw() { ... }
@Test
void rejectsOverdraft() { ... }
}
}JUnit 4 had no built-in equivalent.
Dynamic Tests
JUnit 5 adds @TestFactory for generating tests at runtime:
@TestFactory
Stream<DynamicTest> currencyCodes() {
return Stream.of("USD", "EUR", "GBP", "JPY")
.map(code -> dynamicTest(
"accepts " + code,
() -> assertTrue(validator.isValid(code))
));
}Display Names
@Test
@DisplayName("rejects withdrawal when balance is insufficient")
void rejectsOverdraft() { ... }Works on classes too. Improves readability in test reports without needing descriptive method names.
Migration Setup
Maven: run JUnit 4 and JUnit 5 side by side
<dependencies>
<!-- JUnit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.0</version>
<scope>test</scope>
</dependency>
<!-- Run existing JUnit 4 tests during migration -->
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.11.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
</plugin>
</plugins>
</build>Gradle
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:5.11.0")
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.11.0")
}
tasks.test {
useJUnitPlatform()
}Step-by-Step Migration Strategy
1. Add JUnit 5 without removing JUnit 4
Add junit-jupiter and junit-vintage-engine as shown above. All existing JUnit 4 tests continue to pass via the Vintage engine.
2. Migrate new tests to JUnit 5
Write all new tests using JUnit 5 APIs. Don't touch existing tests yet.
3. Migrate existing tests file by file
For each test class:
- Update import statements
- Rename annotations (
@Before→@BeforeEach, etc.) - Remove
publicmodifiers from test methods - Replace
@Test(expected = ...)withassertThrows - Replace
@Test(timeout = ...)withassertTimeout - Replace
@RunWithwith@ExtendWith - Replace
@Rulefields with@ExtendWithor JUnit 5 built-ins
4. Migrate Mockito
Update to mockito-junit-jupiter:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.12.0</version>
<scope>test</scope>
</dependency>Replace @RunWith(MockitoJUnitRunner.class) with @ExtendWith(MockitoExtension.class).
5. Remove JUnit 4 dependency
Once all tests are migrated, drop junit:junit and junit-vintage-engine from your build file.
Common Migration Issues
Static @BeforeAll/@AfterAll methods
JUnit 5 requires these to be static by default (like JUnit 4's @BeforeClass). If you want non-static lifecycle methods on all tests in a class, annotate with @TestInstance(Lifecycle.PER_CLASS):
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class StatefulTest {
private Connection conn;
@BeforeAll
void openConnection() {
conn = dataSource.getConnection(); // not static
}
@AfterAll
void closeConnection() {
conn.close();
}
}@Rule rules with no JUnit 5 equivalent
Custom rules need to be rewritten as extensions. The Extension interface has many extension points: BeforeEachCallback, AfterEachCallback, ParameterResolver, TestExecutionExceptionHandler, etc.
Spring: use @SpringJUnitConfig or @ExtendWith(SpringExtension.class)
JUnit 4:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest { ... }JUnit 5:
@SpringBootTest // SpringExtension is included via @SpringBootTest in Spring 5+
class ServiceTest { ... }Testing with HelpMeTest
JUnit 5 unit tests cover the logic layer. For full-stack validation — whether the feature works end-to-end in a real browser — HelpMeTest runs Robot Framework + Playwright tests in plain English, with no source code access required.
This is especially useful when migrating: your JUnit 5 tests guard the unit level, HelpMeTest guards the user-visible behavior, and the two layers complement each other across the migration.
Summary
| Concern | JUnit 4 | JUnit 5 |
|---|---|---|
| Lifecycle | @Before, @After, @BeforeClass, @AfterClass |
@BeforeEach, @AfterEach, @BeforeAll, @AfterAll |
| Expected exceptions | @Test(expected = ...) |
assertThrows() |
| Timeouts | @Test(timeout = ...) |
assertTimeout() |
| Extension | @RunWith (one runner) |
@ExtendWith (multiple) |
| Rules | @Rule, @ClassRule |
Extensions + built-ins (@TempDir) |
| Parameterized | Parameterized runner |
@ParameterizedTest + source annotations |
| Nested | Not supported | @Nested |
| Dynamic tests | Not supported | @TestFactory |
| Test visibility | Must be public |
Can be package-private |
Migrate incrementally using the Vintage engine — there's no need for a big-bang rewrite.