Gherkin is a plain-text language used in Behavior-Driven Development (BDD) to describe how software should behave. In Cucumber, we use Gherkin syntax to write test cases in a structured, readable format. The core goal is to bridge the gap between technical and non-technical stakeholders by describing software behavior in plain English (or other supported natural languages).
In this section, we’ll cover the features of Gherkin, its annotations (keywords), syntax structure, and a sample written in English.
Gherkin supports multiple languages, listed here: Gherkin Language Support
Gherkin Structure (Given - When - Then Format)
Gherkin syntax revolves around a set of structured keywords used to describe scenarios:
Feature: Describes a high-level functionality or business requirement. This is the title of the feature file and may include a short description.
Scenario: Represents a specific example or test case. Each scenario tests one behavior or flow within the feature.
Given: Sets up the initial context or preconditions for the scenario. It defines the starting state of the system.
When: Describes the main action or event performed by the user or system.
Then: Specifies the expected outcome after the action is performed.
And / But: Extend the meaning of Given, When, or Then for better readability and to avoid repetition. These steps follow the context of the previous keyword.
Background: Defines steps that are common to all scenarios in the feature. Useful for setting shared preconditions.
Scenario Outline: Used to create data-driven tests by running the same scenario with multiple sets of inputs.
Examples: A table of input values passed into the scenario placeholders.
Gherkin Syntax Example for Login Feature
This example demonstrates how Gherkin is used to define a behavior of successful login in a way that is both human-readable and executable by Cucumber.