Effective Testing - Test Structure

written in effective-testing-series, testing, tests

One way to make sure your tests are readable is to have them all adhere to the same structure.

By far, the most common structure is “Given - When - Then” (aka “Arrange, Act, Assert”). It goes like this:

  1. On Given: We create the objects and set up the needed state.
  2. On When: We perform the action we want to test.
  3. On Then: We validate the state changed as expected.

For example:

The comments explaining each section are optional, and can be omitted on trivial scenarios like the one shown here.

Note how we use whitespace to clearly separate each section. Anybody familiar with the structure will be able to easily identify each section at a glance.

Some testing libraries like Kotest support a style that already includes the Given, When and Then keywords, making the structure explicit.


This post is part of the Effective Testing Series.


Comments