Difference between JUnit 4 and JUnit 5
Explore the key distinctions between JUnit 4 and JUnit 5, focusing on annotation changes, test lifecycle hooks, and Java Development Kit compatibility. This lesson prepares you to migrate your unit tests to JUnit 5 with clarity on updated features and support.
This lesson will help us understand the differences between JUnit 4 and JUnit 5.
JUnit 4 and JUnit 5 comparison
The table below shows a side-by-side comparison of annotations used in JUnit 4 and JUnit 5.
JUnit 5 | JUnit 4 |
@Test | @Test |
@BeforeEach | @Before |
@BeforeAll | @BeforeClass |
@AfterEach | @After |
@AfterAll | @AfterClass |
@Disabled | @Ignore |
@Tag | @Category |
@ExtendWith | @RunWith |
Code example using JUnit 4
Below is a unit test code written in JUnit 4.
- We define the test with the
@Testannotation from the packageorg.junit. - We use the
@BeforeClass,@Before,@After, and@AfterClassare used to hook into the life cycle of theJUnit 4tests. - We use the
@Ignoreannotation to skip the execution of a given test.
Code example using JUnit 5
Below is a unit test code written in JUnit 5.
- We define the test with the
@Testannotation from theorg.junit.jupiter.apipackage. - We use
@BeforeAll,@BeforeEach,@AfterEach, and@AfterAllto hook into the life cycle of theJUnit5tests. - The
@Disabledannotation is used to skip the execution of a given test.
Java Development Kit (JDK) compatibility
The main difference to keep in mind before migrating to JUnit 5 is the JDK Compatibility.
JUnit 4 supports JDK 5 and later versions. JUnit 5 supports JDK 8 and later versions.