Search⌘ K

Arrange, Act, and Assert Your Way to a Test

Explore the Arrange Act Assert (AAA) pattern to write clear and maintainable unit tests in Java. Learn how to setup test data, execute methods under test, and assert expected outcomes using JUnit with Java 8 features like lambda expressions. Understand test-driven development importance and how to verify failing tests for reliable code validation.

A Test Case

Let’s start with a scenario that provides an example of the expected behavior of the target code. To test a ScoreCollection object, we can add the numbers 5 and 7 to the object and expect that the arithmeticMean method will return 6 (because (5+7)/2 is equal to 6).

Remember that naming is important. We call this test answersArithmeticMeanOfTwoNumbers, which nicely summarizes the scenario laid out in the test method.

Run the modified ScoreCollectionTest below to check if it passes.

//We are testing ScoreCollection.java which you can find in left
//panel. Junit-test > src > iloveyouboss > ScoreCollection.java

package iloveyouboss;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*; 
import org.junit.*;

public class ScoreCollectionTest {
   @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));
   }
}
ScoreCollectionTest.java

The output OK (1 test) shows that we have ...