liveBook · Manning

Given-when-then pattern

As explained in Unit Testing Principles, Practices, and Patterns

A test-structuring pattern that divides a test into given, when, and then phases corresponding to setup, execution, and verification.

The Given-When-Then pattern structures a unit test into three readable phases: Given establishes the system under test and dependencies, When invokes the behavior, and Then verifies the outcome. The outcome may be a return value, final state, or interaction with collaborators. Its uniformity reduces test-suite maintenance costs and makes tests more accessible to non-programmers. section 3.1

Calculator test

Given two numbers and a calculator, When the calculator sums them, Then the result is 30. Keeping these phases distinct makes the behavior immediately visible. Multiple Given-When-Then groups suggest that one test verifies too many things and should be split. section 3.1

Listing 3.1. A test covering the Sum method in calculator
public class CalculatorTests                             #1
{
    [Fact]                                               #2
    public void Sum_of_two_numbers()                     #3
    {
        // Arrange
        double first = 10;                               #4
        double second = 20;                              #4
        var calculator = new Calculator();               #4

        // Act
        double result = calculator.Sum(first, second);   #5

        // Assert
        Assert.Equal(30, result);                        #6
    }
}

Use the calculator listing to see the pattern applied in a concrete unit test. section 3.1

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines three phases, maps them to Arrange-Act-Assert, and warns against tests containing multiple phase groups.
Examples
Uses calculator addition and a store purchase test to demonstrate phase boundaries and observable outcomes.
What it assumes
Assumes familiarity with unit tests and introduces the correspondence between Given-When-Then and Arrange-Act-Assert.
What you can do after
Apply the pattern to write readable unit tests with explicit setup, execution, and outcome verification.
How it connects
Connects unit testing with Arrange-Act-Assert and Test-Driven Development.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.