Java Shot #3: Document Arrange, Act and Assert sections while writing Unit tests

A unit test can be broken down into three segments.

  1. Arrange
  2. Act and
  3. Assert

In Arrange step, you would build the necessary data that is needed for execution of the test case along with that you can also setup Mock functionality.

In the Act step, you will actually call the method that needs to be tested.

In the Assert step, you would validate the actual response values with the expected response values.


Presence of these three segments is something known to majority of the engineers who write test cases frequently - even engineers who wrote test cases once or twice, would have written the test cases following the arrange-act-assert pattern.

As a best practice, I recommend adding a comment at the start of each segment to denote the beginning of that segment.

Sample Java code without Arrange-Act-Assert documentation 😦

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

    @Test
    public void testAddition() {
        Calculator calculator = new Calculator();
        int a = 5;
        int b = 3;
        int expectedSum = 8;
        int actualSum = calculator.add(a, b);
        assertEquals(expectedSum, actualSum);
    }
}

Sample Java code without Arrange-Act-Assert documentation 😦

If you see in the above code, it's quite complicated to understand where the each section ends.


Sample Java code without Arrange-Act-Assert documentation and newline between sections 🙂

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

    @Test
    public void testAddition() {
        
        Calculator calculator = new Calculator();
        int a = 5;
        int b = 3;
        int expectedSum = 8;

        int actualSum = calculator.add(a, b);

        assertEquals(expectedSum, actualSum);
    }
}

Sample Java code without Arrange-Act-Assert documentation and newline between sections 🙂

You can add newline to specify the sections but it's not explicitly clear what's the importance of the newline.

To be more explicit, you can add a comment and that makes a lot of difference.


Sample Java code with Arrange-Act-Assert documentation😁

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

    @Test
    public void testAddition() {
        // Arrange
        Calculator calculator = new Calculator();
        int a = 5;
        int b = 3;
        int expectedSum = 8;

        // Act
        int actualSum = calculator.add(a, b);

        // Assert
        assertEquals(expectedSum, actualSum);
    }
}

Sample Java code with Arrange-Act-Assert documentation😁