Course contentsShow
← Computer Science
Lesson 2225 of 2,87250. Software TestingFree lesson

Anatomy of a Unit Test

Learn the Arrange-Act-Assert pattern and the structure of a well-written unit test.

Anatomy of a Unit Test

You'll learn: How to structure a clean, readable unit test using the Arrange-Act-Assert pattern.

Every well-written unit test follows a three-part structure that makes it easy to understand what's being tested and why. Think of it like a scientific experiment: you set up your materials, perform the experiment, then check the results.

The Arrange-Act-Assert Pattern

Arrange is where you set up everything needed for the test. Create objects, initialize variables, configure mock data—essentially prepare your test environment. This is like gathering ingredients before cooking.

Act is the single action you're testing. Call the function or method being tested with your arranged inputs. This should typically be one line—you're testing one specific behavior.

Assert is where you verify the outcome. Check that the result matches your expectations using assertion statements. Did the function return the right value? Did it modify state correctly? This confirms your "experiment" worked as predicted.

Example Structure (Conceptual)

// Arrange
input = 5
calculator = new Calculator()

// Act
result = calculator.square(input)

// Assert
assert result equals 25

Notice how readable this is: you can instantly see what's being tested (square function), with what input (5), and what the expected outcome is (25).

Why This Matters

This pattern enforces single responsibility for tests—each test validates one specific behavior. When a test fails, you immediately know which part broke: setup issues appear in Arrange, logic bugs in Act, and incorrect assumptions in Assert.

Some teams add two optional sections: Guard (precondition checks before Arrange) and Teardown (cleanup after Assert), but AAA remains the core.

Key Takeaway: The Arrange-Act-Assert pattern structures unit tests into setup, execution, and verification phases, making tests self-documenting and failures easy to diagnose.