In Cucumber, the Background keyword is used to define common steps that are executed before each scenario in a feature file. It helps avoid repetition when multiple scenarios have the same initial steps or setup.
Why Use Background?
When several scenarios share the same set of preconditions or initial context, instead of copying those steps into each scenario, you define them once in a Background section. This improves:
Readability
Maintainability
DRY (Don't Repeat Yourself) principle
Syntax of Background keyword in feature file:
Feature: User Login Feature Background: Given The user is on the login page Scenario: Successful Login with valid credentials When The user enters valid username and password Then The user should be redirected to the dashboard Scenario: Login fails with invalid credentials When The user enters invalid username or password Then An error message should be displayed
The step '
Given The user is on the login page' is common for both scenarios and will be executed before each scenario.Java Step Definition Example
public class LoginSteps { @Given("The user is on the login page") public void user_is_on_login_page() { System.out.println("User navigates to login page"); } @When("The user enters valid username and password") public void enter_valid_credentials() { System.out.println("User enters valid credentials"); } @When("The user enters invalid username or password") public void enter_invalid_credentials() { System.out.println("User enters invalid credentials"); } @Then("The user should be redirected to the dashboard") public void redirected_to_dashboard() { System.out.println("User is on dashboard"); } @Then("An error message should be displayed") public void error_message_displayed() { System.out.println("Error message shown"); } }
At a glance:
| Keyword | Purpose |
|---|---|
| Background | Defines steps that run before each scenario |
| Scenario | A single test case in a feature |
| Given | Preconditions or setup |
| When | Action performed |
| Then | Expected outcome |
Important Points:
Only one
Backgroundis allowed per feature file.It runs before each
ScenarioorScenario Outlinein the feature file.It should not be overused — if too many steps go into
Background, scenarios may become hard to understand.