Fact-checked by Grok 2 weeks ago

Given-When-Then

The Given-When-Then format is a templating structure for expressing behavioral specifications in , particularly within (BDD), where scenarios are articulated as: Given some initial context or preconditions, When a specific action or event occurs, and Then the expected outcomes or verifiable results follow. This approach, pioneered by Dan North (also known as Daniel Terhorst-North), Chris Matts, and Liz Keogh, transforms abstract requirements into concrete, human-readable examples that bridge the gap between business stakeholders, analysts, testers, and developers. Introduced in North's 2006 article "Introducing BDD," the format draws inspiration from domain-driven design's emphasis on ubiquitous language and templates to create criteria that reduce ambiguity in software specifications. By structuring scenarios this way—such as "Given the account balance is $100, When the user withdraws $50, Then the balance should be $50"—it enables automated testing tools like and JBehave to parse and execute these descriptions as living documentation. The format aligns closely with testing patterns like Arrange-Act-Assert, enhancing clarity in business-facing tests while promoting collaboration across teams.

Overview

Definition

The Given-When-Then format is a structured template used in for writing executable specifications that describe the expected behavior of a system in a clear and unambiguous manner. It serves as a semi-structured way to articulate scenarios, making them readable and understandable to both technical developers and non-technical stakeholders, such as product owners or business analysts. This format emerged as a key practice within agile methodologies to bridge the gap between requirements and implementation by focusing on concrete examples of system behavior. The template consists of three distinct parts: "Given" establishes the initial context or preconditions of the scenario, setting up the necessary or assumptions; "When" describes the action, event, or stimulus that triggers the behavior under test; and "Then" specifies the expected outcomes or verifiable results that should follow from the action. For instance, in a banking application , "Given" might state that an balance is $100, "When" the user withdraws $50, and "Then" the balance is updated to $50. This breakdown ensures that each is self-contained and focused, facilitating automated testing while maintaining human readability. The primary purpose of the Given-When-Then format is to promote clarity in requirements by avoiding vague descriptions and instead using precise, example-driven narratives that can be directly translated into tests. It embodies the principles of , where concrete instances illustrate rules and behaviors, allowing teams to validate understanding collaboratively and generate living documentation that evolves with the software. By emphasizing verifiable outcomes, the format reduces misunderstandings and supports of requirements into development workflows.

Components

The Given-When-Then structure comprises three distinct components that together form a clear, readable specification for software behavior in (BDD). Each component serves a specific role in articulating the scenario, ensuring that the description remains focused, testable, and accessible to both technical and non-technical stakeholders. The Given component sets the initial context and preconditions, describing the state of the system or environment before the scenario unfolds. It establishes what is true at the outset, such as the user's status, existing data, or environmental assumptions, without incorporating any actions or changes. For instance, it might specify "Given that a user account has a balance of $100," focusing solely on setup to provide a shared understanding of the starting point. Guidelines for effective use emphasize writing in the to maintain a declarative tone, avoiding imperative language or implementation details, and keeping the description concise to ensure business readability. While some frameworks like recommend past tense for Given to denote prior events, the original formulation uses for across components. The When component identifies the trigger or action that initiates the behavior under test, typically limited to a single, focused event to maintain clarity. It captures user interactions, system calls, or external stimuli, such as "When the user submits a withdrawal request for $50," without delving into the underlying . This singularity prevents scenarios from becoming overly complex, allowing the component to highlight the precise stimulus for the observed outcome. Writing guidelines advise using present tense and an active, imperative-like voice for the action to convey immediacy, while steering clear of technical jargon to prioritize business-oriented language. The Then component outlines the expected observable outcomes and verifications resulting from the When action, emphasizing measurable results and assertions for success or failure conditions. It focuses on what should be true afterward, such as "Then the account balance should be $50," without explaining causal reasons or internal processes. This ensures the specification remains verifiable through external checks, like UI displays or API responses. Best practices include present tense phrasing, declarative assertions free of side effects, and brevity to facilitate and review; multiple outcomes can be chained with "And" for completeness. Overall, effective writing across these components involves present tense for uniformity, an imperative voice in When to denote actions, and a to conciseness and business-readable prose to bridge domain experts and developers. This approach enhances collaboration by making specifications self-explanatory and executable as tests.

History

Origins in BDD

The Given-When-Then structure was pioneered by Dan North (also known as Daniel Terhorst-North) in the early 2000s as a core element of (BDD), which emerged to resolve common challenges in (TDD), such as confusion over where to begin testing, what constitutes meaningful tests, and the lack of clear intentions in test specifications. Working at , North collaborated with Chris Matts toward the end of 2004 to propose the Given-When-Then format as a template for defining requirements and acceptance criteria, expanding BDD's scope beyond code to include . This approach was developed during North's creation of JBehave, an early BDD framework started in late 2003, to make agile practices more accessible for teams struggling with TDD's technical focus. North's first formal proposal of Given-When-Then appeared in his 2006 article "Introducing BDD," where he presented it as a simple, conversational sentence template for structuring scenarios: "Given [some initial context], when [a significant event happens], then [ensure some observable outcome]." The template was designed to promote readability by using that mimics how stakeholders discuss features, thereby shifting emphasis from implementation details to expected behaviors. Influenced by Eric Evans' , which advocates for a "ubiquitous language" shared across teams, and agile methodologies emphasizing collaboration, Given-When-Then aimed to bridge communication gaps between developers, testers, and business stakeholders. Early motivations centered on enhancing test expressiveness—drawing from tools like agiledox for generating readable documentation from tests—to ensure specifications were focused on rather than low-level code concerns, fostering better alignment in agile environments.

Adoption and Evolution

In 2008, Aslak Hellesøy integrated the Given-When-Then structure into the Gherkin syntax as part of the framework, establishing it as a standardized for (BDD) specifications. This move separated the syntax from the underlying tool, enabling broader reusability across different implementations and facilitating the creation of human-readable, executable scenarios. By 2013, the structure gained significant popularity through Martin Fowler's influential blog post, which detailed its application in , emphasizing how it bridges communication between technical and non-technical stakeholders. This exposition helped solidify Given-When-Then as a core practice in agile methodologies, promoting its use beyond initial BDD contexts. The evolution of Given-When-Then progressed from manual specifications to automated tests throughout the 2010s, with widespread adoption in agile teams for defining acceptance criteria. Key milestones included its influence on tools such as SpecFlow, released in late 2009 to support .NET environments, and JBehave, an early BDD framework from 2003 that incorporated the structure to enable narrative-driven testing. By the 2020s, usage expanded into and / (CI/CD) pipelines, where tools like and its .NET successor Reqnroll (following SpecFlow's end-of-life in December 2024) integrate with platforms such as Jenkins and Actions to automate at scale. This growth reflects a projected for BDD tools, driven by enhanced collaboration and in modern development environments.

Usage

In Behavior-Driven Development

In Behavior-Driven Development (BDD), the Given-When-Then format serves as a foundational structure for expressing user stories and scenarios, forming a core element of the ubiquitous language that aligns business stakeholders, developers, and testers around shared domain concepts. This language ensures that requirements are articulated in plain, business-oriented terms, driving development cycles by focusing on observable behaviors rather than implementation details. For instance, scenarios written in this format describe preconditions (Given), actions (When), and outcomes (Then), making them accessible and executable as specifications. The format integrates deeply into the BDD process through collaborative practices, particularly in "" meetings involving the product owner, developer, and tester, where scenarios are drafted to clarify requirements and serve as living documentation that evolves with the project. These sessions emphasize dialogue to uncover ambiguities, ensuring the scenarios reflect real user needs and remain a throughout the lifecycle. Within the BDD workflow, Given-When-Then fits across three key phases: discovery, where teams collaboratively explore and write initial scenarios to identify valuable behaviors; formulation, which refines these into precise, structured examples; and automation, where the steps are implemented as code to verify the system's adherence to the specifications. This progression shifts emphasis from technical tests to business outcomes, enabling iterative refinement. By prioritizing expected behaviors from the user's perspective, the format reduces miscommunication across roles, fostering better alignment and minimizing rework through its focus on concrete examples over abstract descriptions. This approach enhances overall team productivity and ensures that development efforts deliver verifiable value.

In Acceptance Testing

In , the Given-When-Then structure serves as a template for creating executable specifications that map directly to automated tests. These specifications, often written in syntax, describe acceptance criteria for user stories, where the "Given" clause establishes the initial context or preconditions, the "When" clause outlines the action or event under test, and the "Then" clause verifies the expected outcomes. This approach transforms natural language scenarios into code-implemented functions through step definitions in frameworks like , enabling the tests to run against the application and fail until the behavior is correctly implemented. The role of Given-When-Then in is to verify the completion of user stories by executing these as part of suites, ensuring that new changes do not break existing functionality. Integrated with tools such as , JBehave, or SpecFlow, the structure supports pipelines, where tests are automated to provide rapid feedback on whether the system meets acceptance criteria. For instance, a might be implemented to check a banking feature, running repeatedly to confirm reliability across development cycles. Best practices for applying Given-When-Then in emphasize creating reusable and independent steps to promote and reduce duplication. Steps should be written in , with "Given" focusing on setup without side effects, "When" on isolated actions, and "Then" on assertions using query methods. To handle variations within scenarios, data tables—known as "Examples" in —are used to parameterize tests efficiently, allowing multiple iterations with different inputs without rewriting steps. For example:
Scenario Outline: Eating cucumbers
  Given I have <start> cucumbers
  When I eat <eat> cucumbers
  Then I should have <left> cucumbers

Examples:
  | start | eat | left |
  | 12    | 5   | 7    |
  | 20    | 5   | 15   |
This ensures tests remain concise and focused on behavior verification. Given-When-Then relates closely to Acceptance Test-Driven Development (ATDD) by guiding a test-first approach, where teams collaboratively define acceptance criteria upfront using this format to align on expected behaviors before coding begins. This upfront specification helps bridge the gap between business requirements and technical implementation, fostering automated tests that evolve as living documentation of the system's acceptance standards.

Examples

Basic Example

A basic example of the Given-When-Then format illustrates the structure using a straightforward withdrawal scenario, where the system behavior is specified in to ensure clarity and shared understanding among stakeholders. This format, introduced by Dan North in 2006 as part of (), promotes specifications that bridge technical and business perspectives. In syntax—a used by tools like for writing scenarios—the example appears as plain text with structured keywords:
Feature: ATM Withdrawal

Scenario: Successful withdrawal with sufficient funds
  Given the account has sufficient funds
  When the user requests a [withdrawal](/page/Withdrawal)
  Then the money is dispensed and the balance is updated
This Gherkin representation leverages the keywords "Given," "When," and "Then" to organize the scenario into distinct parts, allowing automation while remaining human-readable. Step-by-step, the "Given" clause sets the initial context by describing preconditions, such as the account balance being adequate for the transaction, which establishes a reproducible starting point for the behavior. The "When" clause then details the triggering action, here the user's withdrawal request, simulating the event that prompts the system to respond. Finally, the "Then" clause verifies the anticipated result, confirming that the ATM dispenses the cash and adjusts the balance, thereby validating the system's correctness. This example qualifies as basic because it confines itself to a single action without additional complexities, demonstrating the format's core and enhancing for beginners and non-technical users alike.

Advanced Example

An advanced example of the Given-When-Then structure appears in the context of an checkout process, where multiple preconditions establish a realistic user state, actions involve conditional logic like discount application, and outcomes require verifications across updates, database persistence, and external notifications. This scenario illustrates scalability for larger features by incorporating a section for shared setup, "And" keywords to chain related steps without altering the core Given-When-Then flow, and separate scenarios to handle variations such as valid and invalid discounts, thereby addressing edge cases efficiently. The following feature file snippet demonstrates this for a checkout system:
Feature: [E-commerce](/page/E-commerce) Checkout with Discounts

  Background:
    Given a user is logged in with valid payment details
    And the user's cart contains 2 items totaling &#36;100

  Scenario: Successful discount application during checkout
    When the user proceeds to checkout
    And the user applies [discount](/page/Discount) code "SAVE20"
    Then the order total should update to &#36;80
    And the order should be confirmed in the database
    And a confirmation [email](/page/Email) should be sent to the user

  Scenario: Invalid discount code during checkout
    When the user proceeds to checkout
    And the user applies discount code "INVALID10"
    Then the order total should remain &#36;100
    And an error message "Invalid discount code" should display on the UI
In this structure, the Background provides initial context by simulating a logged-in with pre-populated cart items, ensuring reusable setup across scenarios. The Given clause within each scenario implicitly builds on this by assuming the cart state, while the When steps capture sequential actions: initiating checkout and attempting application, which may involve conditional validation against a promotions database. The Then clauses verify outcomes appropriate to each case—for the valid , multifaceted results including UI reflection of the adjusted total (e.g., via text assertion), backend of the , and with an email service for notification; for the invalid case, an error display to handle the failure without proceeding to confirmation—highlighting the structure's ability to test end-to-end flows and edge cases. This approach with distinct scenarios promotes maintainability for real-world features like rules.

Variations and Extensions

Multiple Steps

In the Given-When-Then format, complex workflows involving multiple actions and outcomes can be expressed by chaining additional "When" and "Then" steps after the initial "Given" setup, allowing scenarios to describe sequential behaviors without breaking them into separate examples. For instance, a scenario might begin with preconditions in "Given," followed by a first action in "When" and its result in "Then," then proceed to a subsequent "When" for the next action and another "Then" for its verification. This approach maintains the logical flow of the behavior while capturing multi-step interactions, as seen in early BDD formulations where scenarios model real-world sequences of outcomes. To extend steps within the same without repetition, the "And" and "But" keywords are used to continue "Given," "When," or "Then" clauses, improving readability and natural language flow. "And" connects additional similar conditions or expectations, such as multiple preconditions ("Given the account is active And the balance is sufficient"), while "But" introduces contrasting outcomes to highlight exceptions or nuances ("Then the withdrawal succeeds But the balance updates correctly"). These keywords do not alter step matching in tools like but ensure the scenario reads conversationally, aligning with BDD's emphasis on ubiquitous language. Guidelines for multiple steps stress avoiding over-complication by limiting scenarios to 3-5 steps total, splitting lengthy sequences into distinct scenarios if they represent independent behaviors to prevent ambiguity and maintain focus as executable specifications. This ensures each scenario tests a single, cohesive behavior while preserving clarity for stakeholders. For common patterns like loops or iterations, direct repetition within a scenario is discouraged; instead, scenario outlines with examples tables are preferred for data-driven variations, reserving chained steps for essential sequential logic.

Integration with Tools

Cucumber, a prominent BDD framework, utilizes Gherkin syntax in .feature files to define Given-When-Then scenarios, where each step is linked to corresponding step definitions implemented in programming languages such as Ruby or Java. These step definitions map natural language phrases from the Gherkin steps to executable code, enabling automation of acceptance tests. Cucumber further supports tagging to categorize scenarios for selective execution and hooks for setup and teardown actions before or after scenarios. Other BDD tools extend Given-When-Then to additional ecosystems, including SpecFlow for .NET environments, which employs feature files and step definitions in C# to facilitate behavior specifications within IDEs or pipelines like . Similarly, Behave for parses steps into Python-based step implementations, allowing seamless execution in IDEs such as or with CI tools like Jenkins for automated testing workflows. These frameworks enable Given-When-Then scenarios to run as unit or tests, promoting between developers, testers, and stakeholders. In implementation, step definitions in these tools match Gherkin phrases to methods using regular expressions for flexible , capturing dynamic parameters like user inputs or values to drive test logic. Reporting capabilities include generation of for visual summaries of pass/fail outcomes and for machine-readable results, integrable with tools like Jenkins for dashboards. By 2025, modern adaptations have incorporated AI-assisted test generation, where tools analyze requirements to auto-create Given-When-Then scenarios in format for or compatible frameworks, reducing manual authoring efforts. Additionally, integration with cloud testing platforms such as allows parallel execution of scenarios across distributed instances, enhancing for large-scale BDD test suites.

Benefits and Criticisms

Advantages

The Given-When-Then format promotes clarity and collaboration by providing a structured, English-like template that uses to describe system behaviors, making it accessible to non-technical stakeholders such as business analysts and product owners while enabling developers and testers to align on requirements without ambiguity. This ubiquitous language fosters shared understanding across multidisciplinary teams, reducing miscommunication and encouraging early discussions during requirement formulation. It enables automation by allowing scenarios written in this format to be directly mapped to executable code through tools like , which translates syntax into automated tests that integrate seamlessly with frameworks such as , thereby minimizing manual validation efforts and supporting pipelines. This direct translatability ensures that acceptance criteria evolve into reliable, runnable specifications that verify intended behaviors efficiently. The format supports living documentation by generating business-readable artifacts from automated tests, which remain synchronized with the as they are validated through execution, providing an authoritative, up-to-date reference for system features that evolves alongside the product. These executable specifications serve as a , accessible to all team members and reducing the need for separate, static documents that often become outdated. Furthermore, it improves overall quality by emphasizing observable behaviors in scenarios, which helps identify requirements gaps during collaborative discovery sessions before implementation begins, thereby catching potential issues early in the development cycle. The measurable outcomes defined in the "Then" steps facilitate precise , as failing tests clearly indicate deviations from expected behaviors, leading to more robust software with fewer defects and lower maintenance costs.

Limitations

The Given-When-Then format, while structured, can introduce in scenarios describing complex systems, where detailed and multiple outcomes necessitate extensive step definitions, thereby increasing the overall length of specifications and elevating maintenance overhead. This rigid structure may not accommodate all testing needs, such as that relies on ad-hoc discovery or UI-heavy interactions requiring visual or validations beyond predefined behaviors, limiting its applicability in dynamic or non-linear scenarios. Adopting the format presents a , particularly for non-technical stakeholders who may find it challenging to articulate precise phrasing that aligns with the template's requirements, and over-reliance on associated tools can complicate documentation for simpler use cases. In large-scale projects, scalability issues arise from difficulties in reusing steps across scenarios and managing duplication, which can lead to comprehension problems, slower execution, and heightened maintenance efforts without rigorous practices to enforce consistency.

References

  1. [1]
  2. [2]
    Given When Then - Martin Fowler
    Aug 21, 2013 · It's an approach developed by Daniel Terhorst-North and Chris Matts as part of Behavior-Driven Development (BDD).Missing: original source
  3. [3]
    History of BDD - Cucumber
    Nov 14, 2024 · Behavior-driven development was pioneered by Daniel Terhorst-North back in the early 00s, as he explained in a 2006 article called Introducing BDD.Missing: original | Show results with:original
  4. [4]
    Introducing BDD | Dan North & Associates Limited
    Sep 20, 2006 · Using the given-when-then template, the first two scenarios might look like this: Scenario: Account is in credit Given the account is in ...Missing: source | Show results with:source
  5. [5]
    What is "Given - When - Then"? - Agile Alliance
    (Given) some context; (When) some action is carried out; (Then) a particular set of observable consequences should obtain. An example: Given my bank account is ...
  6. [6]
    Reference - Cucumber
    Jan 26, 2025 · Each step starts with Given , When , Then , And , or But . Cucumber executes each step in a scenario one at a time, in the sequence you've ...
  7. [7]
    What is BDD (Behavior Driven Development)? | Agile Alliance
    2004: Chris Matts and Dan North proposed the given-when-then canvas to expand the scope of BDD to business analysis and documents; 2004: in order to test his ...Behavior Driven Development... · Expected Benefits · Signs Of UseMissing: original | Show results with:original<|control11|><|separator|>
  8. [8]
    BDD Tool Cucumber is 10 Years Old: Q&A with its Founder Aslak ...
    Apr 30, 2018 · Cucumber combines requirements specifications, automated tests and living documentation into a single format called Gherkin, which is just plain ...
  9. [9]
    Is BDD Dying? - Automation Panda
    Mar 6, 2025 · Scenarios also need structure. Gherkin is the go-to language for BDD because its Given-When-Then steps follow the Arrange-Act-Assert pattern.
  10. [10]
    The birth of SpecFlow: Chronicles of an open source project
    Sep 12, 2013 · Finally we presented SpecFlow to the world: on October 22nd 2009 we committed SpecFlow on GitHub. Gaspar: This was my first OSS project and it ...Missing: initial | Show results with:initial
  11. [11]
    JBehave 2.0 is live! | Dan North & Associates Limited
    Sep 7, 2008 · The jbehave.org domain was registered and the first lines of code written on Christmas Eve 2003, much to my wife's bemusement.Missing: initial | Show results with:initial
  12. [12]
    What is BDD? (Behavior-Driven Development) - BrowserStack
    Dec 17, 2024 · From understanding the adoption statistics of BDD to diving deep into its process, benefits, challenges, tools, and best practices, we've ...Missing: 2010s 2020s<|control11|><|separator|>
  13. [13]
    Behaviour-Driven Development | Cucumber
    ### Summary of Given-When-Then in BDD Process
  14. [14]
  15. [15]
    Step definitions - Cucumber
    Dec 13, 2024 · When Cucumber executes a Gherkin step in a scenario, it will look for a matching step definition to execute. The I have 48 cukes in my belly ...
  16. [16]
    Cucumber reference
    Mar 28, 2025 · Recall that step definitions start with a preposition or an adverb ( Given , When , Then , And , But ). ... example: com.example.glue
  17. [17]
    Tutorial - behave 1.4.0.dev0 documentation
    The “Given”, “When” and “Then” parts of this prose form the actual steps that will be taken by behave in testing your system. These map to Python step ...
  18. [18]
    Reporting - Cucumber
    Dec 19, 2024 · cucumber_characteristics - Generates HTML/JSON reports on overall test timings, as well as timings and usage of Steps, Features, and Examples. ...Cucumber Reports Service​ · Custom Formatters​ · Formatter Api​
  19. [19]
    Cucumber Testing: A Key to Generative AI in Test Automation
    Feb 27, 2025 · Cucumber testing enhances test automation by enabling AI-driven scenario generation, maintenance, and smarter test coverage.
  20. [20]
    Test Automation using Selenium and Cucumber Framework: Tutorial
    Learn how to use Selenium Cucumber to create & run automated tests with examples. Read tutorial to understand cucumber framework, steps to execute & best ...
  21. [21]
    Isn't the business readable documentation just overhead? - Cucumber
    Apr 9, 2021 · Automation – the documentation is automated, creating living documentation that verifies the system's behaviour. In the following sections ...Missing: Given- advantages
  22. [22]
    What is Cucumber Framework? (Benefits of Cucumber Testing)
    Tests are more user-focused and based on the system's behavior. In BDD, “Given-When-Then” is the proposed approach for writing test cases. Consider the example ...
  23. [23]
    Understanding Behavior Driven Development Testing - Testlio
    Oct 4, 2024 · Create Scenarios Using the Given/When/Then Format. For each user story, outline specific scenarios using the Given/When/Then method. A ...
  24. [24]
    Behavior Driven Development with Gherkin BDD Testing - Testsigma
    Sep 15, 2025 · It uses specific keywords like Given, When, Then to describe the expected behavior of a feature. This format makes Gherkin tests readable and ...Gherkin Syntax And Structure · How To Write Gherkin Tests · Gherkin In Practice: Tools...Missing: e- | Show results with:e-
  25. [25]
    The tragedy of Given-When-Then. | The IT Risk Manager
    Apr 6, 2019 · In 2010, Nat Pryce and team created a spredsheet based eco-system where traders entered the examples. Once again Given-When-Then was not used.
  26. [26]
    Behavior Driven Testing: Elevating Software Quality - Functionize
    Sep 5, 2024 · In a 2006 blog, Dan North explained the origins of BDD. “Behaviour-driven development started life as an NLP exercise to stem the abuse of ...Missing: original | Show results with:original
  27. [27]
    [PDF] Maintaining Behaviour Driven Development Specifications
    “Given-When-Then” structure [1], [2], [3]. This gives a specification that is expressed in non-technical, domain- specific terms, that should be readable ...