0
0
JUnittesting~10 mins

assertEquals in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if the add method of a simple calculator returns the correct sum of two numbers using assertEquals.

Test Code - JUnit 5
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

    @Test
    public void testAdd() {
        Calculator calc = new Calculator();
        int result = calc.add(2, 3);
        assertEquals(5, result, "2 + 3 should equal 5");
    }
}

class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes CalculatorTest-PASS
2Calculator object is createdCalculator instance ready for use-PASS
3Calls add(2, 3) methodMethod executes and returns 5-PASS
4assertEquals checks if expected 5 equals actual 5Comparison of expected and actual valuesassertEquals(5, 5)PASS
5Test finishes successfullyTest marked as passed in report-PASS
Failure Scenario
Failing Condition: The add method returns a wrong sum, e.g., 4 instead of 5
Execution Trace Quiz - 3 Questions
Test your understanding
What does assertEquals verify in this test?
AThat the method throws an exception
BThat the method runs without errors
CThat the expected value matches the actual result
DThat the object is not null
Key Result
Use assertEquals to compare expected and actual values clearly, providing a helpful message to understand failures.