0
0
JUnittesting~5 mins

Arrange-Act-Assert pattern in JUnit

Choose your learning style9 modes available
Introduction

The Arrange-Act-Assert pattern helps organize tests clearly. It makes tests easy to read and understand by separating setup, action, and verification.

When writing a new unit test for a method or function.
When you want to clearly show what is being tested and how.
When debugging tests to find which step fails.
When teaching others how to write clean and simple tests.
When maintaining tests to quickly understand their purpose.
Syntax
JUnit
/* Arrange */
// Prepare objects and set initial state

/* Act */
// Call the method or perform the action to test

/* Assert */
// Check the results with assertions

Arrange: Set up everything needed for the test.

Act: Perform the action you want to test.

Assert: Verify the outcome of the action.

Examples
This test checks if adding 2 and 3 returns 5.
JUnit
@Test
void testSum() {
    // Arrange
    Calculator calc = new Calculator();

    // Act
    int result = calc.add(2, 3);

    // Assert
    assertEquals(5, result);
}
This test verifies that a new list is empty.
JUnit
@Test
void testIsEmpty() {
    // Arrange
    List<String> list = new ArrayList<>();

    // Act
    boolean empty = list.isEmpty();

    // Assert
    assertTrue(empty);
}
Sample Program

This test checks that after adding "Apple" to the list, the list size is 1 and the first item is "Apple".

JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;

class ListTest {

    @Test
    void testAddItem() {
        // Arrange
        List<String> fruits = new ArrayList<>();

        // Act
        fruits.add("Apple");

        // Assert
        assertEquals(1, fruits.size());
        assertEquals("Apple", fruits.get(0));
    }
}
OutputSuccess
Important Notes

Keep each test focused on one behavior for clarity.

Use comments or blank lines to separate Arrange, Act, and Assert steps.

Good naming helps understand what each test does.

Summary

Arrange-Act-Assert separates test setup, action, and verification.

This pattern makes tests easier to read and maintain.

Use it to write clear and simple unit tests.