Q9 of 21 · BDD / Cucumber

What are hooks in Cucumber, what types exist, and what should (and shouldn't) go in them?

BDD / CucumberMidbddcucumberhooksbeforeafterlifecycle

Short answer

Short answer: Hooks are functions that run at specific points in the test lifecycle — @Before, @After (per scenario), @BeforeStep, @AfterStep (per step), and @BeforeAll/@AfterAll (once per suite). Use them for setup/teardown, not for test logic.

Detail

Hook types and order:

BeforeAll  → once before entire suite
  Before   → before each Scenario
    BeforeStep → before each step
    AfterStep  → after each step (even on failure)
  After    → after each Scenario (even on failure)
AfterAll   → once after entire suite

Java:

@Before
public void setUp(Scenario scenario) {
    driver = new ChromeDriver();
    this.scenario = scenario;
}

@After
public void tearDown(Scenario scenario) {
    if (scenario.isFailed()) {
        byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        scenario.attach(screenshot, "image/png", "failure-screenshot");
    }
    driver.quit();
}

JavaScript:

Before(async function() {
  this.page = await browser.newPage();
});

After(async function({ result }) {
  if (result.status === Status.FAILED) {
    const screenshot = await this.page.screenshot();
    await this.attach(screenshot, 'image/png');
  }
  await this.page.close();
});

What belongs in hooks:

  • Browser/driver start and quit
  • DB connection setup and teardown
  • Screenshot capture on failure
  • Auth token retrieval (once in @BeforeAll)

What doesn't belong in hooks:

  • Business logic or assertions — that belongs in step definitions
  • Scenario-specific setup — that belongs in Given steps (so it's visible in the feature file)
  • Complex conditional logic — hooks that branch on the scenario name are a smell

// WHAT INTERVIEWERS LOOK FOR

All four hook types and their order. The isFailed() screenshot pattern is a strong example. Clear understanding of what should NOT go in hooks.