Given-When-Then

Given-When-Then is a commonly used structure for describing examples in Behavior Driven Development, often also called “scenarios”.

Gherkin scenarios use the Given-When-Then structure. However, Given-When-Then can be also used in other domain-specific languages, testing and specification frameworks.

  • Given describes only those parts of the system state which are relevant for the rules illustrated in the scenario. Well-written “Given” statements should focus only on the relevant state necessary for understanding the example and omit other details. They should describe the current system state rather than the previous user actions that lead to that state.
  • When describes a user action triggering the desired system behavior with the given system state. Ideally, this is written in an active voice from a user perspective. It usually describes a user’s input to a user interface or a client’s call to a service interface.
  • Then describes how the system should behave (react) in the described example scenario in terms of providing value to the user. This can be the primary user who triggered the behavior (acting in “When”) or secondary users interacting with the system in other ways. Many teams express assertions in the “Then” section using the modal “should” to emphasize an expectation that needs to be tested to be true (manually or automatically).

Given-When-Then examples can be compared to bug reports since both describe the steps to produce an expected system behavior. However, the Given-When-Then example is typically written before the system is implemented and omits the erroneous behavior, while the bug report is written after the system has been implemented and also contains the error:

  • Given-When-Then
  • Given
  • When
  • Then
  • (omitted)
  • Bug Report
  • Preconditions, steps to reproduce
  • Final step to reproduce the error
  • Expected behavior
  • Erroneous behavior

Given-When-Then can be also compared to the “Triple-A” testing pattern which is well known in unit testing:

  • Given-When-Then
  • Given
  • When
  • Then
  • Triple A testing pattern
  • Arrange
  • Act
  • Assert

Example:

Scenario: Add two numbers

Given I have entered 50 into the calculator

And I have entered 70 into the calculator

When I press add

Then the result should be 120 on the screen

💡 Quickly write, download and share your own Gherkin feature files and scenarios with our free Online Gherkin Editor.

Check out our “Given When Then With Style” blog post series.

Learn all the tricks to write better feature specifications.