0
0
JUnittesting~10 mins

Arrange-Act-Assert pattern in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if the Calculator class correctly adds two numbers using the Arrange-Act-Assert pattern. It verifies that the sum of 5 and 3 equals 8.

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() {
        // Arrange
        Calculator calculator = new Calculator();
        int a = 5;
        int b = 3;

        // Act
        int result = calculator.add(a, b);

        // Assert
        assertEquals(8, result, "Sum should be 8");
    }
}

class Calculator {
    public int add(int x, int y) {
        return x + y;
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes CalculatorTest class-PASS
2Arrange: Create Calculator instance and set inputs a=5, b=3Calculator object created, variables a=5, b=3 assigned-PASS
3Act: Call add method with a and bCalculator.add(5, 3) called, returns 8-PASS
4Assert: Check if result equals 8Result is 8assertEquals(8, result)PASS
5Test ends successfullyTest passed with no errors-PASS
Failure Scenario
Failing Condition: Calculator.add method returns incorrect sum
Execution Trace Quiz - 3 Questions
Test your understanding
What is the purpose of the 'Arrange' step in this test?
ACall the method being tested
BCheck the test result
CSet up objects and inputs needed for the test
DClean up after the test
Key Result
Using the Arrange-Act-Assert pattern helps keep tests clear and organized by separating setup, action, and verification steps.