0
0
JUnittesting~10 mins

Unit testing concept in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks a simple method that adds two numbers. It verifies the method returns the correct sum.

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 - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2CalculatorTest class loadedCalculatorTest and Calculator classes ready-PASS
3testAdd method invokedCalculator object created-PASS
4add method called with arguments 2 and 3Inside add method, inputs received-PASS
5add method returns 5Result 5 returned to testAdd-PASS
6assertEquals checks if result equals 5Comparing expected 5 and actual 5assertEquals(5, result)PASS
7Test completes successfullyTest runner records pass-PASS
Failure Scenario
Failing Condition: add method returns incorrect sum
Execution Trace Quiz - 3 Questions
Test your understanding
What does the testAdd method verify?
AThat the Calculator class exists
BThat adding 2 and 3 returns 5
CThat the add method throws an exception
DThat 2 plus 3 equals 6
Key Result
Unit tests should focus on small pieces of code, like one method, to check they work correctly in isolation.