liveBook · Manning

Callback

As explained in BDD in Action, Second Edition

A hook is a framework callback method that runs before or after a specified software execution event.

A business-readable scenario should describe behavior, not instructions for opening a browser or resetting a database. A hook is a callback method that runs at a defined point in the test life cycle, keeping that technical work out of the scenario. section 8.5.2 section 8.5.1

Choose the hook's timing to match the work:

  • Before a scenario, prepare reference data or reset database state so the scenario can run independently of other scenarios. section 8.5.2
  • After a scenario, clean up resources or use its name and status when logging the result. section 8.5.2
  • Before or after the whole test run, start and stop resources that should be shared across scenarios. section 8.5.2

Run browser setup only where needed

Tag a browser-driven scenario @web. A matching Before hook creates its ChromeDriver, and a matching After hook closes it. Scenarios without that tag do not need the browser setup. section 8.5.2 section 7.4.7

Listing 8.21 Hook methods that only run for specific scenarios
WebDriver driver;
 
@Before("@web")
public void prepareDriver() {       #1
    driver = new ChromeDriver();
}
 
@After("@web")                      #2
public void closeBrowser() {
    driver.quit();
}

The Java example pairs @Before("@web") and @After("@web") around browser use. section 8.5.2

Use a Background step instead when the setup is information business readers need, such as a flight-points schedule. Keep implementation-dependent housekeeping in hooks. Cucumber provides hook examples in Java and TypeScript; hook details vary across BDD tools. section 8.5.1 section 8.5.2

How BDD in Action, Second Edition covers it

How deep it goes
Defines lifecycle callbacks and demonstrates scenario-level, tag-specific, and test-run hooks, while noting that implementation details vary by tool.
Examples
Shows database reference-data setup, result logging, tagged ChromeDriver setup and cleanup, and test-run database-container management.
What it assumes
Assumes familiarity with scenarios and step definitions, but defines hooks and distinguishes them from business-facing Background steps.
What you can do after
Apply it via Cucumber hooks to isolate scenarios and manage browser or database resources at the appropriate lifecycle point.
How it connects
Connects hooks to Gherkin tags, Background steps, scenario independence, database setup, and browser automation.

Also explained in

Compare how 19 books explain callback →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of BDD in Action, Second Edition. The section links point to the parts of the book it draws on.