Arrange, Act, Assert
a.k.a. Given, When, Then
Part six of a series of posts about automated testing.
There is a guideline for structuring individual unit tests, known as “Arrange, Act, Assert”. The idea is, most tests should be structured in this manner:
That is, these steps are clearly separated, and there is usually a single assertion at the end.
When more than one test has a similar “Arrange” step, it is often possible to factor out a setup method:
In general, it can be useful to shorten tests by writing helper methods for common boilerplate steps. This maximizes the signal-to-noise ratio of the test itself - you see just the condition, and the assertion.
There are potentially some exceptions to the idea that you have one assertion per test. For example, tests which specifically exercise changes in state:
The key is to have one test per behaviour.