Follow the AAA Pattern

Learn about making effective tests by following the AAA pattern.

We'll cover the following

When we write tests, we visually organize them into three chunks: arrange, act, and assert, also known as triple-A (AAA).

@Test
public void answersArithmeticMeanOfTwoNumbers() {
   // Arrange
   ScoreCollection collection = new ScoreCollection();
   collection.add(() -> 5);
   collection.add(() -> 7);
      
   // Act
   int actualResult = collection.arithmeticMean();
      
   // Assert
   assertThat(actualResult, equalTo(6));
  }
}

Previously, we added comments to identify each of the chunks explicitly, but these comments add no value once we understand the AAA acronym.

AAA is a part of just about every test we’ll write.

Arrange

Before we execute the code we’re trying to test, ensure that the system is in a proper state by creating objects, interacting with them, calling other APIs, and so on. In some rare cases, we won’t arrange anything because the system is already in the state we need.

Act

We then need to exercise the code we want to test, usually by calling a single method.

Assert

Then we verify that the exercised code behaved as expected. This can involve inspecting the exercised code’s return value or the new state of any objects involved. It can also involve verifying that interactions between the tested code and other objects took place.

The blank lines that separate each portion of a test are indispensable visual reinforcement to help us understand a test even more quickly.

After

If running the test results in any resources being allocated, make sure that they get cleaned up.

Get hands-on with 1400+ tech skills courses.