Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Hooks and Tags

Hooks: Before, After and Friends

Learn Cucumber hooks: Before and After, BeforeStep and AfterStep, BeforeAll and AfterAll, execution order, failures in hooks and what the Scenario object offers.

A scenario should say what the system does, not how a database gets cleaned or a browser gets started. Yet every real test suite needs that plumbing: open a session, reset some data, close a window, take a screenshot when something fails. Cucumber gives you hooks for this. A hook is a method that Cucumber calls for you at a fixed point in the life of a scenario, so the plumbing stays out of your Gherkin.

This lesson covers every kind of hook, the order in which they run, what happens when a hook itself fails, and what the Scenario object lets you do. Cucumber itself cannot run on this site, so the real Java code is read-only. The runnable examples are small Java stand-ins that mimic the order of hooks, which is the part that most often surprises people.

Where hooks run

BeforeAll Once, before the whole run.
Before Before every scenario.
BeforeStep Before every step.
After After every scenario, always.
1 / 2

The six hooks

Cucumber-JVM offers these annotations in the package io.cucumber.java:

Hook Runs Notes
@BeforeAll once, before any scenario static method, no arguments (Cucumber 7+)
@Before before each scenario may take a Scenario argument
@BeforeStep before each step also receives a Scenario
@AfterStep after each step runs even if the step failed
@After after each scenario runs even if a step or a @Before hook failed
@AfterAll once, after the last scenario static method, no arguments

Other languages use the same ideas with different spelling: Before and After in Cucumber.js, Before and After blocks in Ruby, and before_scenario style functions in behave.

Java
package shop.steps;

import io.cucumber.java.After;
import io.cucumber.java.AfterAll;
import io.cucumber.java.Before;
import io.cucumber.java.BeforeAll;
import io.cucumber.java.Scenario;

public class Hooks {

    @BeforeAll
    public static void startTestDatabase() {
        TestDatabase.start();          // slow, so do it once
    }

    @Before
    public void resetData(Scenario scenario) {
        TestDatabase.clearTables();    // every scenario starts clean
        System.out.println("Starting: " + scenario.getName());
    }

    @After
    public void report(Scenario scenario) {
        if (scenario.isFailed()) {
            System.out.println("FAILED: " + scenario.getName());
        }
    }

    @AfterAll
    public static void stopTestDatabase() {
        TestDatabase.stop();
    }
}

Hooks can live in any class on the glue path. Many teams keep them together in a class called Hooks, so a newcomer knows where to look.

Order of execution

For one scenario, Cucumber runs things in this order:

  1. all @Before hooks, lowest order first
  2. the steps of the Background, then the scenario's own steps, each wrapped by @BeforeStep and @AfterStep
  3. all @After hooks, highest order first

The reversal for After is deliberate. Think of try and finally blocks: what you set up first should be torn down last. The default order is 10000, and hooks with the same number run in an unspecified order, so give an explicit number whenever one hook depends on another.

Java
@Before(order = 10)   // runs first
public void startBrowser() { }

@Before(order = 20)   // runs second, may use the browser
public void login() { }

@After(order = 10)    // runs last
public void closeBrowser() { }

@After(order = 20)    // runs first: logout while the browser is still open
public void logout() { }

Notice that login has a higher number than startBrowser for @Before, and logout has the higher number for @After so it goes first. The same idea, mirrored.

Run the stand-in below and change the order numbers to watch the sequence change.

Java Hook order stand-in (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Failures inside hooks

What if something goes wrong in a hook?

  • If a @Before hook throws, the remaining @Before hooks and all the steps are skipped, the scenario fails, and @After hooks still run, so cleanup happens.
  • If a step fails, later steps are skipped, but @AfterStep for that step and all @After hooks still run.
  • If an @After hook throws, the scenario is marked failed, and other @After hooks still run.

Because @After may run when setup never completed, write cleanup defensively: check that the browser or the connection exists before you close it.

Java
@After
public void closeBrowser() {
    if (driver != null) {
        driver.quit();
    }
}
Java After hooks run after a failure (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Steps hooks and the Scenario object

@BeforeStep and @AfterStep are handy for taking a screenshot after every step or logging timing, but they run for every step, so keep them cheap. A hook method may take one Scenario parameter. Useful members:

Member Meaning
getName() the scenario name
getId() a unique id
getSourceTagNames() all tags, including inherited ones
getStatus() PASSED, FAILED, SKIPPED, UNDEFINED, ...
isFailed() shortcut for a failed status
getUri(), getLine() where the scenario lives
log(String) add text to the report
attach(byte[], mediaType, name) add a file such as a screenshot
Java
@AfterStep
public void screenshotOnFailure(Scenario scenario) {
    if (scenario.isFailed()) {
        byte[] png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        scenario.attach(png, "image/png", "failure");
    }
}

Note that the status is the status of the scenario so far inside @AfterStep, and the final status inside @After.

Common mistakes

  • Heavy work in @Before for every scenario. Starting a browser or database for each scenario can dominate run time. Put one-time setup in @BeforeAll, and only reset state per scenario. Hooks that need tags are covered in Tags and filtering.
  • Business setup hidden in hooks. If the scenario only makes sense when a customer exists, say so in a Given step. Hooks are for technical setup. See Test data setup and cleanup.
  • Relying on the order of equal numbers. Give an explicit order.
  • Sharing mutable static fields. Hooks and steps run in the same thread per scenario; share state through objects, as shown in Scenario state and dependency injection.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In what order do two @After hooks with order 10 and order 20 run?

    After hooks run in descending order so that what was set up first is torn down last.
  2. 2. A step fails in the middle of a scenario. Which statement is true?

    Later steps are skipped, but After and AfterStep hooks always run so that cleanup and screenshots can happen.
  3. 3. Which hooks must be static methods without parameters in Cucumber-JVM 7 and later?

    BeforeAll and AfterAll run once, outside any scenario, so they are static and cannot receive a Scenario.
  4. 4. Where should the business fact 'a customer with a gold account exists' be set up?

    Hooks are for technical plumbing. Facts the scenario depends on belong in the Gherkin.

Summary

  • Hooks run code around scenarios and steps so the Gherkin stays about behavior.
  • @BeforeAll and @AfterAll run once; @Before and @After per scenario; @BeforeStep and @AfterStep per step.
  • @Before runs in ascending order, @After in descending order; the default is 10000.
  • @After runs even after failures, so write cleanup defensively.
  • The Scenario object gives name, tags, status, logging and attachments.

Next: Tags and filtering