← Back to libraryQuestion 255 of 468
🥒Cucumber / BDDIntermediate

Hooks — @Before, @After, and Tagged Hooks

📌 Definition:

Hooks are blocks of code that run before/after scenarios (or steps) for technical setup and teardown — @Before, @After, @BeforeStep, @AfterStep — kept out of the Gherkin to preserve readability.

📖 Detailed Explanation:

@Before runs before each scenario (start browser, reset data), @After runs after (quit browser, capture screenshot on failure, cleanup). Tagged hooks run only for matching scenarios: @Before('@db') runs only before scenarios tagged @db. Hook ORDER can be set, and @After hooks receive the Scenario object to check status (scenario.isFailed()) and attach screenshots. Keep business preconditions in Background/Given and technical plumbing in hooks. Hooks are the Cucumber equivalent of setUp/tearDown and are crucial for driver lifecycle and failure diagnostics.

🔑 Key Points:
  • @Before/@After: per-scenario technical setup/teardown
  • Tagged hooks (@Before('@db')) run only for matching scenarios
  • @After gets the Scenario (isFailed()) → screenshot on failure
  • Keep technical plumbing in hooks, not in Gherkin
🌍 Real-World Example:

@After public void tearDown(Scenario s) { if (s.isFailed()) s.attach(screenshot, 'image/png', 'failure'); driver.quit(); } — attaches a screenshot only when a scenario fails, then closes the browser.

🎯 Scenario-Based Interview Question:

You need a browser started before every scenario, a screenshot only on failure, and DB seeding only for @db scenarios. How do hooks handle this?