Given-When-Then is a commonly used structure for describing examples in Behavior Driven Development, often also called “scenarios”. For example, Gherkin scenarios use the Given-When-Then structure. However, Given-When-Then can be also used in other DSLs and testing/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 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: