JUnit 4 vs JUnit 5: Key Differences and When to Use Each
JUnit Platform and Jupiter. Unlike JUnit 4, which uses a single monolithic jar, JUnit 5 separates concerns into modules and supports more flexible extensions and annotations.Quick Comparison
This table summarizes the main differences between JUnit 4 and JUnit 5.
| Aspect | JUnit 4 | JUnit 5 |
|---|---|---|
| Architecture | Single monolithic jar | Modular: Platform, Jupiter, Vintage |
| Annotations | Uses @Test, @Before, @After | Adds @BeforeEach, @AfterEach, @Test with more options |
| Extension Model | Limited, uses Rules and Runners | Powerful extension model with Extension API |
| Java Version Support | Java 5+ | Java 8+ (uses lambdas and streams) |
| Test Engine Support | Only JUnit 4 tests | Supports multiple test engines including JUnit 4 via Vintage |
| Dynamic Tests | Not supported | Supports dynamic tests with @TestFactory |
Key Differences
JUnit 5 introduces a new architecture split into three main modules: JUnit Platform for launching tests, JUnit Jupiter for writing tests and extensions, and JUnit Vintage to run legacy JUnit 4 tests. This modular design allows better flexibility and integration with modern tools.
The annotation model in JUnit 5 is more expressive and consistent. For example, @BeforeEach replaces @Before, and @AfterEach replaces @After, making test lifecycle methods clearer. Also, JUnit 5 supports new annotations like @DisplayName for better test reporting.
Extension support is a major upgrade in JUnit 5. Instead of the older Rules and Runners in JUnit 4, JUnit 5 uses a powerful Extension API that allows developers to customize test behavior more flexibly, including parameter injection, conditional test execution, and lifecycle callbacks.
Code Comparison
import org.junit.Test; import static org.junit.Assert.assertEquals; public class CalculatorTest { @Test public void addition() { int result = 2 + 3; assertEquals(5, result); } }
JUnit 5 Equivalent
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class CalculatorTest { @Test void addition() { int result = 2 + 3; assertEquals(5, result); } }
When to Use Which
Choose JUnit 5 when starting new projects or when you want modern features like modularity, better extension support, and Java 8+ compatibility. It offers more flexibility and future-proofing.
Use JUnit 4 if you maintain legacy projects that already depend on it and migration is costly or risky. JUnit 5 supports running JUnit 4 tests via the Vintage engine, easing gradual migration.