
Learn Gherkin and Cucumber, write clear test scenarios, use the right keywords, set up files, run tests, and follow best practices.
Last Modified on: December 7, 2025
Automation testing using Gherkin and Cucumber helps you describe the behavior of a software application in a structured way that both technical and non-technical stakeholders can follow.
You can write test scenarios in Gherkin using natural language, focusing on how the software should behave rather than how it is implemented. Cucumber then maps those scenarios to your automated test scripts.
Overview
What Is Cucumber Framework?
Cucumber is a testing framework that supports Behavior-Driven Development. It allows teams to write clear, readable scenarios in plain text using Gherkin syntax, ensuring software behavior is verified against business requirements.
What Is Gherkin Language?
Gherkin is a structured, domain-specific language used in BDD to write test scenarios in plain text. Using keywords like Feature, Scenario, Given, When, Then, And, and But, it describes software behavior in a way that is understandable by both technical and non-technical stakeholders.
How to Use Gherkin With Cucumber?
Writing and executing tests with Gherkin and Cucumber involves defining features, creating scenarios, and linking them to executable code. The general workflow is:
Cucumber is a testing framework that uses a Behavior-Driven Development (BDD) approach. By leveraging the plain-text Gherkin syntax, it transforms business requirements into executable specifications.
With Cucumber testing, software teams ensure that the entire team shares an understanding of what to build and validate it with automated tests that align with business objectives.
Gherkin is a domain-specific, structured language used in Behavior Driven Development to write test cases in plain text. You can use it to describe software behavior in a way that both technical and non-technical stakeholders can understand.
Its Given, When, Then syntax defines the initial context, the action taken, and the expected outcome. This structure in Gherkin testing turns requirements into precise, executable specifications and helps keep business intent, test coverage, and technical implementation aligned.
Gherkin uses keywords such as Feature for goals, Scenario for user flows, Given for setup, and When for actions. Then defines outcomes, while And or But extend steps clearly and keep scenarios readable.
Example:
Feature: Product SearchExample:
Scenario: Successful product search from the home pageExample:
Scenario: Successful product search from the home pageExample:
When I type "iPhone" into the search fieldExample:
Then the search results page should show products related to "iPhone".Example:
When I type "iPhone" in the search field
And I click on the search buttonNote: Run Cucumber tests on cloud Selenium Grid. Try LambdaTest Now!
To write test scenarios with Gherkin and Cucumber, start by defining the feature you want to test. Then write scenarios using Given for setup, When for user actions, and Then for expected results.
The following test scenario will be demonstrated using Cucumber Java.
Test Scenario:
However, with LambdaTest, we can run tests in parallel across multiple real browsers and devices, get detailed logs, screenshots, and videos for failures, and integrate with CI/CD pipelines.
It makes automation testing with Gherkin Cucumber faster, more reliable, and easier to manage without maintaining local infrastructure.
Implementation:
To implement the test scenario using Gherkin and Cucumber, we need to perform the following three steps:
Let’s create a feature file that uses the Given, When, Then steps to explain the test scenarios:
Feature: Product Search
As a website user
I want to search for products
So that I can quickly find the items I am looking for
Scenario: Successful product search from the home page
Given I am on the LambdaTest E-Commerce Playground home page
When I type "iPhone" into the search field
And I click the search button
Then the search results page should show products related to "iPhone"
The feature file should be created inside the src/test/resources folder. After the feature file is created, Cucumber will show warnings indicating that the steps defined in the file are not implemented.
These warnings can be resolved by creating a step definition file that implements the code for running the steps specified in the feature file.
A step definition file in Cucumber implements the automation code using the Gherkin steps written in feature files. It links the scenarios written in plain text to executable test logic.
The step definition file uses annotations such as @Given, @When, and @Then to define actions and assertions that drive the application under test. A step definition file should be created inside the src/test/java folder.
public class ProductSearchSteps {
private RemoteWebDriver driver;
private final By searchBox = By.cssSelector("#main-header input[name='search']");
private static final String GRID_URL = "@hub.lambdatest.com/wd/hub";
private static final String LT_ACCESS_KEY = System.getenv("LT_ACCESS_KEY");
private static final String LT_USERNAME = System.getenv("LT_USERNAME");
private String status = "failed";
@Before
public void setup() {
try {
this.driver = new RemoteWebDriver(new URL("https://" + LT_USERNAME + ":" + LT_ACCESS_KEY + GRID_URL),
getChromeOptions());
} catch (final MalformedURLException e) {
System.out.println("Could not start the remote session on LambdaTest cloud grid");
}
this.driver.manage()
.timeouts()
.implicitlyWait(Duration.ofSeconds(20));
}
@Given("I am on the LambdaTest E-Commerce Playground home page")
public void i_am_on_the_lambda_test_e_commerce_playground_home_page() {
driver.get("https://ecommerce-playground.lambdatest.io/");
WebElement searchField = driver.findElement(searchBox);
assertTrue(searchField.isDisplayed());
}
@When("I type {string} into the search field")
public void i_type_into_the_search_field(String productName) {
WebElement searchField = driver.findElement(searchBox);
searchField.sendKeys(productName);
}
@And("I click the search button")
public void i_click_the_search_button() {
WebElement searchButton = driver.findElement(By.cssSelector("#search button[type='submit']"));
searchButton.click();
}
@Then("the search results page should show products related to {string}")
public void the_search_results_page_should_show_products_related_to(String productName) {
String headerText = driver.findElement(By.cssSelector("#product-search h1"))
.getText();
assertEquals(headerText, "Search - " + productName);
this.status = "passed";
}
@After
public void tearDown() {
this.driver.executeScript("lambda-status=" + this.status);
driver.quit();
}
public ChromeOptions getChromeOptions() {
final var browserOptions = new ChromeOptions();
browserOptions.setPlatformName("Windows 11");
browserOptions.setBrowserVersion("latest");
final HashMap<String, Object> ltOptions = new HashMap<String, Object>();
ltOptions.put("project", "Cucumber Gherkin Demo");
ltOptions.put("build", "LambdaTest E-Commerce Playground Demo");
ltOptions.put("name", "Automation tests using Cucumber BDD");
ltOptions.put("w3c", true);
ltOptions.put("plugin", "java-testNG");
browserOptions.setCapability("LT:Options", ltOptions);
return browserOptions;
}
}Code Walkthrough:
A TestRunner is the main class that starts and controls the Cucumber tests. Using @CucumberOptions, it specifies the locations of feature and step definition files.
@CucumberOptions(
features = "src/test/resources/features",
glue = {"io.github.mfaisalkhatri.lambdatestecommerce.stepdefinitions"},
plugin = {"pretty"}
)
public class TestRunner extends AbstractTestNGCucumberTests {}The AbstractTestNGCucumberTests class must be extended to the TestRunner class when using the TestNG framework as the TestRunner with Cucumber.
Test Execution:
To execute the tests, right-click on the TestRunner class and click on Run TestRunner. It should start executing the tests on the Chrome browser using the Windows 11 platform on LambdaTest.
The following screenshot indicates that the test was successfully run on the latest version of the Chrome browser on Windows 11 on the LambdaTest cloud grid. It provides additional details such as video recordings, step-by-step test execution, and log details.
The following are the best practices that should be used for writing effective Gherkin test scenarios with Cucumber:
Instead of writing the test scenario as:
Given I go the login page
When I enter "user@admin.com" in the user field
And I enter "password" in the password field
And I click on the Login button
Then I should see the dashboardThe test scenario should be written as follows:
Given I am on the login page
When I login with valid credentials
Then I should see the dashboardScenario Outline: Invalid Login validation
Given I am on the login page
When I enter "<username>" and "<password>"
Then I should see "<message>"
Examples:
| username | password | message |
| | secret | "Username is required"|
| user | | "Password is required"|
| user | wrong | "Invalid credentials" |Gherkin and Cucumber are used for different purposes. Gherkin serves as a specification language, whereas Cucumber acts as an execution engine that interprets and validates these instructions.
Let’s understand the key differences between Cucumber and Gherkin based on different criteria as mentioned below:
| Criteria | Gherkin | Cucumber |
|---|---|---|
| Definition | A Domain-Specific Language (DSL). | A test automation tool/framework. |
| Purpose | To explain the business feature in plain text. | To execute the behaviour specified in the feature files as automated tests. |
| File Format | It uses the .feature file format that contains test scenarios. | It uses the .java, .rb, and .js files called step definition files. |
| Syntax | Feature, Given, When, Then, And/But, Scenario, Examples, etc | It uses programming language syntax. |
| Dependencies | None - Just uses plain text. | It depends on the programming language and testing frameworks. |
| Readability | It is human-readable and can be understood by any non-technical person. | It is code-based and requires technical knowledge for understanding the step definitions. |
| Who Writes It? | It is written collaboratively by business analysts, product owners, developers, and QAs. | Test automation engineers, SDETs, and developers write it. |
| Execution | It cannot be executed alone. | It executed the Gherkin test scenarios using the step definition files. |
| Learning Curve | Low learning curve, as it uses plain text with simple keywords. | The learning curve is high as implementing the step definition requires technical knowledge of programming language and test automation frameworks. |
To summarize, Cucumber and Gherkin play an important role in the Behaviour-Driven Development and test automation. Gherkin captures business requirements in plain text, and Cucumber transforms these specifications into executable validations, ensuring alignment between documentation and implementation.
Although Behaviour-Driven Development is popular among various software teams, it adds an extra layer of abstraction requiring the creation of a feature file and then mapping it to the step definition.
This extra abstraction layer can introduce complexity, especially in Cucumber and Gherkin, where natural language steps, reusable phrases, and underlying automation code must stay perfectly in sync. Managing feature files, step definitions, and multiple annotations across scenarios can make BDD feel harder to scale and maintain despite its readability benefits.
Did you find this page helpful?
More Related Hubs
Start your journey with LambdaTest
Get 100 minutes of automation test minutes FREE!!