0
0
JUnittesting~10 mins

Why assertions verify expected outcomes in JUnit - Test Execution Impact

Choose your learning style9 modes available
Test Overview

This test checks if the addition method returns the correct sum. It verifies the expected outcome using assertions to ensure the method works as intended.

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

public class CalculatorTest {

    public int add(int a, int b) {
        return a + b;
    }

    @Test
    public void testAdd() {
        CalculatorTest calculator = new CalculatorTest();
        int result = calculator.add(2, 3);
        assertEquals(5, result, "Addition result should be 5");
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Creates CalculatorTest instanceCalculatorTest object ready-PASS
3Calls add(2, 3) methodMethod executes and returns 5-PASS
4Assert that result equals 5Result is 5assertEquals(5, result)PASS
5Test ends successfullyTest passed with no errors-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 the assertion in the test verify?
AThat the add method throws an exception
BThat the add method returns the expected sum
CThat the add method returns null
DThat the add method runs without errors
Key Result
Assertions are essential because they confirm that the code behaves as expected, catching errors early by comparing actual results to expected outcomes.