Answer
Hooks vs Background in Cucumber
Side-by-Side Comparison
| Background | Hooks (@Before/@After) | |
|---|---|---|
| Written in | Feature file (Gherkin) | Java step definition class |
| Visible to | Everyone (BA, PMs, non-tech) | Developers only |
| Applies to | Only current feature file | All scenarios (global) |
| Tagged scope | No | Yes (@Before("@login")) |
| Language | Plain English | Java code |
| Purpose | Business preconditions | Technical setup/teardown |
| Mapped in reports | Yes (as scenario steps) | Yes (as Before/After section) |
Background — Business Preconditions
Gherkin
Feature: User Account Management
Background: # ← in .feature file
Given the user is on the login page # ← visible to BA/PO
And the user is logged in # ← plain English
Scenario: View profile
When the user clicks "My Profile"
Then the profile page should load
Scenario: Update email
When the user updates email to "new@test.com"
Then success message should appear
The Background steps run before every scenario in this file only.
Hooks — Technical Setup
Java
package hooks;
import io.cucumber.java.Before;
import io.cucumber.java.After;
import io.cucumber.java.Scenario;
public class Hooks {
// Runs before EVERY scenario across ALL feature files
@Before
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
}
// Runs after EVERY scenario across ALL feature files
@After
public void tearDown(Scenario scenario) {
if (scenario.isFailed()) {
byte[] screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.BYTES);
scenario.attach(screenshot, "image/png", "Failure");
}
driver.quit();
}
// Runs only before scenarios tagged @login
@Before("@login")
public void loginSetup() {
loginPage = new LoginPage(driver);
loginPage.navigateTo();
}
}
When to Use Which
| Use Background | Use Hooks |
|---|---|
| Steps that make sense to non-technical readers | Browser/driver initialization |
| Preconditions specific to one feature area | Taking screenshots on failure |
| Part of the "living documentation" | Database setup/teardown |
| UI navigation steps (Given the user is on...) | Injecting test data via API |
| Visible to BA in sprint review | Configuring test environment |
Execution Order
CODE
@Before hook (global)
→ Background step 1
→ Background step 2
→ Scenario step 1
→ Scenario step 2
→ ...
@After hook (global)
