...

/

Arrange, Act, and Assert Your Way to a Test

Arrange, Act, and Assert Your Way to a Test

This lesson will cover a complete walkthrough of JUnit Testing and a comprehensive breakdown of its process.

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 ...

Access this course and 1400+ top-rated courses and projects.