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
