0
0
JUnittesting~10 mins

JUnit 4 vs JUnit 5 (Jupiter) differences - Test Execution Compared

Choose your learning style9 modes available
Test Overview

This test checks a simple calculator addition method using both JUnit 4 and JUnit 5 styles. It verifies that the addition result is correct and shows how assertions and annotations differ between the two versions.

Test Code - JUnit
JUnit
import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class CalculatorTestJUnit4 {
    @Test
    public void testAdd() {
        Calculator calc = new Calculator();
        int result = calc.add(2, 3);
        assertEquals(5, result);
    }
}

// JUnit 5 version
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class CalculatorTestJUnit5 {
    @Test
    void testAdd() {
        Calculator calc = new Calculator();
        int result = calc.add(2, 3);
        assertEquals(5, result);
    }
}

// Calculator class
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}
Execution Trace - 10 Steps
StepActionSystem StateAssertionResult
1JUnit 4 test runner starts and loads CalculatorTestJUnit4 classJUnit 4 environment ready, test class loaded-PASS
2JUnit 4 runner finds @Test method testAdd() and invokes itCalculatorTestJUnit4 instance created-PASS
3testAdd() calls Calculator.add(2, 3) which returns 5Calculator instance created and method executed-PASS
4JUnit 4 assertEquals(5, result) verifies the result is 5Assertion compares expected and actual valuesassertEquals passes if expected == actualPASS
5JUnit 4 test completes successfullyTest marked as passed-PASS
6JUnit 5 test runner starts and loads CalculatorTestJUnit5 classJUnit 5 environment ready, test class loaded-PASS
7JUnit 5 runner finds @Test method testAdd() and invokes itCalculatorTestJUnit5 instance created-PASS
8testAdd() calls Calculator.add(2, 3) which returns 5Calculator instance created and method executed-PASS
9JUnit 5 assertEquals(5, result) verifies the result is 5Assertion compares expected and actual valuesassertEquals passes if expected == actualPASS
10JUnit 5 test completes successfullyTest marked as passed-PASS
Failure Scenario
Failing Condition: Calculator.add() returns wrong result, e.g., 4 instead of 5
Execution Trace Quiz - 3 Questions
Test your understanding
Which annotation is used to mark test methods in both JUnit 4 and JUnit 5?
A@Test
B@Before
C@RunWith
D@TestMethod
Key Result
Using consistent annotations like @Test and clear assertion imports helps keep tests readable and maintainable across JUnit versions.