The Arrange Act Assert is one of the most important patterns for arranging and formatting unit tests. It keeps the tests readable and easy to maintain. The pattern states that each test should be separated into three parts, the Arrange the Act and the Assert.
Arrange
In the Arrange phase, we make sure that the System Under Test (SUT) will be ready to be initialised in the correct condition. That means that all the collaborators have to be initialised, and the SUT has to be fully isolated from its environment. If the test method does not test the constructor of the SUT, then injecting and initialised the SUT is part of this phase.
Act
In this phase, we invoke the method under test with the arranged parameters.
Assert
In this phase, we assert the results from the Act phase against the expected values.
We should write our tests, trying to assert one concept per unit test. The test should have only one reason to fail. That though does not mean that we should have only one Assert statement in this phase, but that we should have one logical assert.
Example of the three phases in a swift unit test:
Gerard Meszaros in his article about the four phases of a test, he adds also the teardown phase. In the teardown phase, we make sure we bring the environment back to its initial state ( e.g. close connection with database).
Mark Seemann goes on step further and suggests how to separate those three phases. If there are less than three lines in total, then we don’t leave empty lines between them. In the case when there are more than three lines, we should leave an empty line between the, Only when a phase starts to contain many lines, we should add a comment on the beginning of the phase.
Resources
http://xunitpatterns.com/Four%20Phase%20Test.html
https://blog.ploeh.dk/2013/06/24/a-heuristic-for-formatting-code-according-to-the-aaa-pattern/
The so-called “single assert rule” simply means that a test should be a single state transition. Arrange, act, assert. Not: Arrange, act, assert, act, assert, …
— Uncle Bob Martin (@unclebobmartin) December 28, 2018