0
0
JUnittesting~10 mins

Single assertion per test debate in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if the calculator adds two numbers correctly. It uses a single assertion to verify the sum result.

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 testAddition() {
        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 initialized-PASS
2Calculator object createdCalculator instance ready-PASS
3add method called with 2 and 3Method returns 5-PASS
4assertEquals checks if result equals 5Result is 5Verify 5 == 5PASS
5Test endsTest passed successfully-PASS
Failure Scenario
Failing Condition: Calculator add method returns incorrect sum
Execution Trace Quiz - 3 Questions
Test your understanding
What does the single assertion in this test verify?
AThat the Calculator object is created
BThat the sum of 2 and 3 equals 5
CThat the add method is called
DThat the test runner starts
Key Result
Using a single assertion per test helps keep tests clear and easy to understand, making it simpler to find what went wrong when a test fails.