</>

Technology

Cucumber

Difficulty

Intermediate

Interview Question

What is the difference between Hooks and Background in Cucumber?

Answer

Hooks vs Background in Cucumber

Side-by-Side Comparison

BackgroundHooks (@Before/@After)
Written inFeature file (Gherkin)Java step definition class
Visible toEveryone (BA, PMs, non-tech)Developers only
Applies toOnly current feature fileAll scenarios (global)
Tagged scopeNoYes (@Before("@login"))
LanguagePlain EnglishJava code
PurposeBusiness preconditionsTechnical setup/teardown
Mapped in reportsYes (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 BackgroundUse Hooks
Steps that make sense to non-technical readersBrowser/driver initialization
Preconditions specific to one feature areaTaking 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 reviewConfiguring test environment

Execution Order

CODE
@Before hook (global)
    → Background step 1
    → Background step 2
    → Scenario step 1
    → Scenario step 2
    → ...
@After hook (global)

Follow AutomateQA

Related Topics