0
0
JUnittesting~15 mins

JUnit 4 vs JUnit 5 (Jupiter) differences - Automation Approaches Compared

Choose your learning style9 modes available
Verify basic test execution and annotation differences between JUnit 4 and JUnit 5
Preconditions (2)
Step 1: Create a test class using JUnit 4 annotations
Step 2: Write a test method annotated with @Test that asserts 2 + 2 equals 4
Step 3: Run the JUnit 4 test and verify it passes
Step 4: Create a test class using JUnit 5 (Jupiter) annotations
Step 5: Write a test method annotated with @Test that asserts 2 + 2 equals 4
Step 6: Run the JUnit 5 test and verify it passes
Step 7: Observe differences in annotations such as @Before vs @BeforeEach and @After vs @AfterEach
Step 8: Observe that JUnit 5 supports @DisplayName for test methods
✅ Expected Result: Both JUnit 4 and JUnit 5 tests run successfully and pass. Differences in annotations and features like @DisplayName are observed.
Automation Requirements - JUnit 5 (Jupiter)
Assertions Needed:
Assert that 2 + 2 equals 4
Verify that @BeforeEach and @AfterEach methods run before and after each test
Verify that @DisplayName annotation sets the test display name
Best Practices:
Use JUnit 5 Jupiter API consistently
Use @BeforeEach and @AfterEach instead of JUnit 4's @Before and @After
Use descriptive @DisplayName for test methods
Keep test methods small and focused
Use assertions from org.junit.jupiter.api.Assertions
Automated Solution
JUnit
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;

@DisplayName("JUnit 5 Basic Test Class")
public class JUnit5BasicTest {

    @BeforeEach
    void setup() {
        System.out.println("Setup before each test");
    }

    @AfterEach
    void teardown() {
        System.out.println("Teardown after each test");
    }

    @Test
    @DisplayName("Test addition: 2 + 2 = 4")
    void testAddition() {
        assertEquals(4, 2 + 2, "2 + 2 should equal 4");
    }
}

This test class uses JUnit 5 (Jupiter) annotations.

@BeforeEach runs before each test method to setup test conditions.

@AfterEach runs after each test method to cleanup.

@Test marks the test method.

@DisplayName provides a readable name for the test class and method.

assertEquals verifies the expected result.

This shows the key differences from JUnit 4, which uses @Before, @After, and lacks @DisplayName.

Common Mistakes - 3 Pitfalls
Using JUnit 4 annotations like @Before and @After in JUnit 5 tests
Not importing org.junit.jupiter.api.Assertions and using JUnit 4 assertions
Not using @DisplayName to improve test readability
Bonus Challenge

Now add parameterized tests in JUnit 5 to test addition with multiple input pairs

Show Hint