Answer
Background Keyword in Cucumber
Purpose
Background is used to define common precondition steps that should run before every scenario in a feature file. It avoids duplicating the same Given steps in each scenario.
Syntax
Gherkin
Feature: Online Shopping
Background:
Given the user is on the application login page
And the user is logged in with valid credentials
Scenario: Add item to cart
When the user searches for "Laptop"
And clicks "Add to Cart"
Then the cart count should be "1"
Scenario: View cart
When the user navigates to the cart page
Then the cart page should be displayed
In the example above, both scenarios first execute the Background steps before running their own steps.
Background vs Hooks (@Before)
| Background | @Before Hook | |
|---|---|---|
| Written in | Feature file (Gherkin) | Java step definition |
| Visible to | BAs, PMs, non-technical | Developers only |
| Applies to | Current feature file only | All scenarios (by default) |
| Tagged scope | No | Yes (@Before("@login")) |
| Purpose | Business preconditions | Technical setup (driver init) |
Real Example
Gherkin
Feature: Banking Transactions
Background:
Given the user is on the application login page
When the user enters credentials "user01" and "Pass@123"
And the user clicks Login
Then the user should be on the home page
Scenario: Check account balance
When the user clicks on "My Account"
Then the balance should be displayed
Scenario: Transfer funds
When the user initiates a transfer of "$500" to "ACC-456"
Then the transfer confirmation should appear
Key Rules
- ✓Only
Givensteps should be in Background (best practice) - ✓There can be only one
Backgroundper feature file - ✓Background runs before every scenario, including Scenario Outline rows
- ✓Background does NOT run before scenarios in other feature files
