Arrange Act Assert

Jag Reehals thinking on things, mostly product development

What is Arrange Act Assert?

Many years ago, when I first started writing unit tests, I always got to a point where my tests started to look messy.

When I say messy what I mean is it took more then it should have to understand

The problem was worse if you were looking at a test you didn’t write!

I wasn’t the only one with this problem. Many examples in books, blogs and sample code had the same issue.

I then found about using the Arrange Act Assert pattern in unit tests.

From that moment on it was clear to be that tests must be:

It doesn’t matter if you’re someone starting out or a seasoned pro, if you start your unit tests with these three comments, it will help you structure your tests in a way that will allow you to focus on writing better unit tests.

Here’s an example to show what I mean.

If we wanted to test two numbers can be added together, we could write something like this

import { add } from './calc';

test('should be able to add two numbers', () => {
  const firstNumber = 1;
  const secondNumber = 2;
  const result = add(firstNumber, secondNumber)
  expect(result).toBe(3);
});

or we could apply the Arrange Act Assert pattern and have a test that looks like this

import { add } from './calc';

test('should be able to add two numbers', () => {

  // Arrange
  const firstNumber = 1;
  const secondNumber = 2;

  // Act
  const result = add(firstNumber, secondNumber)

  // Assert
  expect(result).toBe(3);
});

Now it is much easier to see:

If you have too much code in any of these sections, you’re probably breaking good unit test best practices by:

If you’re mocking anything, then it’s even more important you follow a pattern like this because setting up what should be returned from a stub should be done in the arrange section.

I’ve heard this pattern being called build, operate, check amongst other things but nothing sticks in your mind better than AAA.

There no ambiguity into what the three words mean and it’s so easy to remember.

All I can say is try it, there no cost, it doesn’t depend or any particular language or test framework, and at worst you only need delete three lines of comments.