Difference between JUnit 4 and JUnit 5 | LambdaTest

Hello! :loudspeaker:

Watch this video to see the difference between JUnit 4 and JUnit 5. If you’re not familiar with the updates, this video is for you! :movie_camera: Check it out now!

#JUnit #Testing #TestAutomation #QA

JUnit 4 and JUnit 5 are both popular testing frameworks for Java, but JUnit 5 introduces several improvements and changes compared to JUnit 4. Here are the key differences:

JUnit 4:

Monolithic architecture: JUnit 4 is a single jar file (junit-4.x.x.jar). Limited extensibility: Customizing and extending JUnit 4 requires writing custom runners or rules, which can be cumbersome.

JUnit 5:

Modular architecture: JUnit 5 is composed of three main modules: JUnit Platform: The foundation for launching testing frameworks on the JVM. JUnit Jupiter: The new programming model and extension model for writing tests and extensions in JUnit 5. JUnit Vintage: Provides backward compatibility to run JUnit 4 and JUnit 3 tests on the JUnit 5 platform. Enhanced extensibility: JUnit 5 provides a more flexible extension model with the @ExtendWith annotation.

As per my knowledge sharing few differences:

Annotations

JUnit 4:

Common annotations include @Test, @Before, @After, @BeforeClass, @AfterClass, @Ignore. JUnit 5:

New annotations and some renamed:

@Test: Same as JUnit 4, but can now be used in combination with other annotations like @Tag.

@BeforeEach: Replaces @Before.

@AfterEach: Replaces @After.

@BeforeAll: Replaces @BeforeClass.

@AfterAll: Replaces @AfterClass.

@Disabled: Replaces @Ignore.

New annotations like @Nested, @Tag, @DisplayName.

To learn more about JUnit annotation, follow this guide:

Adding to Tim,

JUnit 4:

Uses org.junit.Assert for assertions (e.g., assertEquals, assertTrue).
Uses org.junit.Assume for assumptions (e.g., assumeTrue, assumeFalse).

JUnit 5:

Uses org.junit.jupiter.api.Assertions for assertions with additional methods (e.g., assertAll, assertThrows). Uses org.junit.jupiter.api.Assumptions for assumptions with enhanced functionality.

JUnit 4:


Parameterized tests are supported but require a specific runner (@RunWith(Parameterized.class)).

JUnit 5:

Enhanced support for parameterized tests with the @ParameterizedTest annotation and a more flexible API (@ValueSource, @CsvSource, @MethodSource).