Background Keyword in Cucumber

  

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:

KeywordPurpose
BackgroundDefines steps that run before each scenario
ScenarioA single test case in a feature
GivenPreconditions or setup
WhenAction performed
ThenExpected outcome


Important Points:

  • Only one Background is allowed per feature file.

  • It runs before each Scenario or Scenario Outline in the feature file.

  • It should not be overused — if too many steps go into Background, scenarios may become hard to understand.