0
0
JUnittesting~15 mins

Arrange-Act-Assert pattern in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify addition of two numbers using Arrange-Act-Assert pattern
Preconditions (2)
Step 1: Arrange: Create an instance of Calculator
Step 2: Act: Call add method with inputs 5 and 3
Step 3: Assert: Verify the result is 8
✅ Expected Result: The test passes confirming that 5 + 3 equals 8
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the addition result equals expected value
Best Practices:
Use Arrange-Act-Assert pattern clearly separated in test method
Use descriptive test method names
Use JUnit 5 annotations and assertions
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

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

public class CalculatorTest {

    @Test
    void testAdd_TwoNumbers_ReturnsSum() {
        // Arrange
        Calculator calculator = new Calculator();

        // Act
        int result = calculator.add(5, 3);

        // Assert
        assertEquals(8, result, "5 + 3 should equal 8");
    }
}

This test uses the Arrange-Act-Assert pattern:

  • Arrange: We create a Calculator object to prepare for the test.
  • Act: We call the add method with inputs 5 and 3.
  • Assert: We check that the result is 8 using assertEquals.

This clear separation helps understand what is setup, what is tested, and what is verified.

Common Mistakes - 3 Pitfalls
Mixing Arrange, Act, and Assert steps without clear separation
Not using assertions to verify the result
Hardcoding values inside assertions without explanation
Bonus Challenge

Now add data-driven testing with 3 different pairs of numbers to verify addition

Show Hint