Exit course
Chapter 6 of 12 Intermediate 9 min read 2 quick checks Updated

Hooks and Sharing State with PicoContainer

On this page
  1. How Cucumber creates step definition objects
  2. A per-scenario browser
  3. A page object
  4. Hooks
  5. Run it
  6. Do not share state between scenarios

In chapter 3 one class held everything: the browser, the hooks, the test data and the steps. That stops working the moment a second class of step definitions needs the same browser. This chapter splits the project into small classes that share state through dependency injection, moves the browser lifecycle into hooks, and reports each scenario's result to TestingBot.

How Cucumber creates step definition objects#

For every scenario, Cucumber creates a new instance of every glue class that the scenario uses, and throws them away at the end. That is good news: nothing leaks from one scenario into the next through fields. It also means that two step classes cannot share state through fields, and static fields are the wrong fix: they leak between scenarios and break as soon as scenarios run in parallel (chapter 8).

The right fix is to let Cucumber hand the same objects to every class within one scenario. That is what a dependency injection module does. Cucumber-JVM supports several (Spring, Guice, Weld and others); the simplest is PicoContainer, which needs no configuration at all. Add it to the pom:

<dependency>
  <groupId>io.cucumber</groupId>
  <artifactId>cucumber-picocontainer</artifactId>
  <scope>test</scope>
</dependency>

The version comes from the cucumber-bom. With PicoContainer on the classpath, any glue class can ask for objects in its constructor. PicoContainer creates each requested class once per scenario and passes the same instance to everyone who asks for it.

A per-scenario browser#

The shared object is a small holder for the WebDriver. The DriverFactory from chapter 3 moves to a support package unchanged:

package com.example.support;

import org.openqa.selenium.WebDriver;

/** One per scenario: PicoContainer creates it and hands the same instance to every class that asks. */
public class Browser {

    private WebDriver driver;

    public void start(String scenarioName) {
        driver = DriverFactory.create(scenarioName);
    }

    public WebDriver driver() {
        if (driver == null) {
            throw new IllegalStateException("No browser: is the @Before hook in the glue path?");
        }
        return driver;
    }

    public boolean isStarted() {
        return driver != null;
    }

    public void quit() {
        if (driver != null) {
            driver.quit();
            driver = null;
        }
    }
}

A page object#

The Selenium calls move out of the step definitions into a page class that also takes the Browser in its constructor:

package com.example.pages;

import com.example.support.Browser;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SignInPage {

    private static final String URL = "https://the-internet.herokuapp.com/login";

    private final Browser browser;

    public SignInPage(Browser browser) {
        this.browser = browser;
    }

    public void signIn(String username, String password) {
        WebDriver driver = browser.driver();
        driver.get(URL);
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("password")).sendKeys(password);
        driver.findElement(By.cssSelector("button[type=submit]")).click();
    }

    public String flashMessage() {
        return new WebDriverWait(browser.driver(), Duration.ofSeconds(10))
                .until(ExpectedConditions.visibilityOfElementLocated(By.id("flash")))
                .getText();
    }

    public void waitForSecureArea() {
        new WebDriverWait(browser.driver(), Duration.ofSeconds(10))
                .until(ExpectedConditions.urlContains("/secure"));
    }

    public void signOut() {
        browser.driver().findElement(By.cssSelector("a[href='/logout']")).click();
        new WebDriverWait(browser.driver(), Duration.ofSeconds(10))
                .until(ExpectedConditions.urlContains("/login"));
    }

    public String heading() {
        return browser.driver().findElement(By.tagName("h2")).getText();
    }
}

waitForSecureArea() and signOut() wait for the URL to change, and flashMessage() waits for the message to be visible instead of reading it straight after the click. On a remote browser the page takes longer to load than on your laptop, and a step that reads the old page "just after" a click is the classic way a suite becomes flaky. The flaky tests course covers that whole family of bugs.

The step definitions now ask for the page object and contain no Selenium at all:

package com.example.steps;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.example.pages.SignInPage;
import com.example.support.Field;
import com.example.support.Member;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import java.util.Map;

public class SignInSteps {

    private final SignInPage signInPage;
    private Member member;

    public SignInSteps(SignInPage signInPage) {
        this.signInPage = signInPage;
    }

    @Given("{member} has an account")
    public void hasAnAccount(Member member) {
        this.member = member;
    }

    @Given("{member} is signed in")
    public void isSignedIn(Member member) {
        this.member = member;
        signInPage.signIn(member.username(), member.password());
        signInPage.waitForSecureArea();
    }

    @When("{member} signs in with his/her password")
    public void signsInWithPassword(Member member) {
        signInPage.signIn(member.username(), member.password());
    }

    @When("someone signs in as {string} with password {string}")
    public void someoneSignsIn(String username, String password) {
        signInPage.signIn(username, password);
    }

    @When("someone signs in with:")
    public void someoneSignsInWith(Map<String, String> credentials) {
        signInPage.signIn(credentials.get("username"), credentials.get("password"));
    }

    @When("he/she signs out")
    public void signsOut() {
        signInPage.signOut();
    }

    @Then("he/she sees {string}")
    public void sees(String message) {
        String flash = signInPage.flashMessage();
        assertTrue(flash.contains(message), () -> "Expected \"" + message + "\" in \"" + flash + "\"");
    }

    @Then("he is in the secure area")
    public void heIsInTheSecureArea() {
        assertTrue(signInPage.flashMessage().contains("You logged into a secure area!"));
        assertEquals("Secure Area", signInPage.heading());
    }

    @Then("the sign-in is rejected because the {field} is invalid")
    public void rejectedBecause(Field field) {
        String expected = switch (field) {
            case USERNAME -> "Your username is invalid!";
            case PASSWORD -> "Your password is invalid!";
        };
        assertTrue(signInPage.flashMessage().contains(expected),
                () -> "Expected \"" + expected + "\" in \"" + signInPage.flashMessage() + "\"");
        assertEquals("Login Page", signInPage.heading());
    }
}

The new steps serve a second feature file, src/test/resources/features/sign_out.feature:

Feature: Signing out

  @smoke
  Scenario: Tom signs out
    Given Tom is signed in
    When he signs out
    Then he sees "You logged out of the secure area!"

Given Tom is signed in is context, so its step definition waits until the secure area has loaded before the When runs.

PicoContainer resolves the chain on its own: SignInSteps needs a SignInPage, which needs a Browser, which has a no-argument constructor. No annotations, no configuration file.

BasketSteps needs the browser that SignInSteps used earlier in the same scenario. What is the right way to share it?

The DI container gives every class the same instance within a scenario and a fresh one for the next. A static field leaks between scenarios and threads, and Cucumber-JVM refuses to load a glue class that extends another class defining step definitions or hooks.

Hooks#

Hooks are methods that run around scenarios and steps. They live in any glue class; a dedicated Hooks class keeps them easy to find.

Annotation Runs Typical use
@BeforeAll / @AfterAll Once, before or after all scenarios. Must be public static. Start a shared service, seed reference data
@Before Before every scenario Start a browser, reset state
@After After every scenario, also when it failed Report the result, quit the browser
@BeforeStep / @AfterStep Around every step Screenshot after a failed step

Hooks can take a Scenario argument, which gives you the name, tags and status, and lets you attach files to the report. They can be limited to tagged scenarios, for example @Before("@admin"), and ordered with order: @Before hooks run from low to high order, @After hooks from high to low, so the first thing set up is the last thing torn down.

Here is the project's Hooks class. Like everything else, it gets the Browser from PicoContainer:

package com.example.support;

import io.cucumber.java.After;
import io.cucumber.java.AfterStep;
import io.cucumber.java.Before;
import io.cucumber.java.Scenario;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

public class Hooks {

    private final Browser browser;

    public Hooks(Browser browser) {
        this.browser = browser;
    }

    @Before
    public void startBrowser(Scenario scenario) {
        browser.start(scenario.getName());
    }

    @AfterStep
    public void screenshotOnFailure(Scenario scenario) {
        if (scenario.isFailed() && browser.isStarted()) {
            byte[] png = ((TakesScreenshot) browser.driver()).getScreenshotAs(OutputType.BYTES);
            scenario.attach(png, "image/png", "failed step");
        }
    }

    @After
    public void stopBrowser(Scenario scenario) {
        if (!browser.isStarted()) {
            return;
        }
        try {
            if (DriverFactory.onTestingBot()) {
                String status = scenario.isFailed() ? "failed" : "passed";
                ((JavascriptExecutor) browser.driver()).executeScript("tb:test-result=" + status);
            }
        } finally {
            browser.quit();
        }
    }
}
  • @AfterStep takes a screenshot as soon as a step fails and attaches it to the scenario. It shows up embedded in target/cucumber.html, and in the console as Embedding failed step [image/png 39387 bytes].
  • @After reports the result to TestingBot before quitting. tb:test-result=passed or failed is a special script that the grid intercepts instead of running in the page; the annotating tests docs list the other values it accepts, such as tb:test-name and tb:test-build. It must run before quit(), because after that there is no session to send it to. The finally makes sure the browser is closed even if reporting fails.

An @After hook calls driver.quit() and then executeScript("tb:test-result=failed"). What do you see on TestingBot?

Reporting is a WebDriver command inside the session. Once quit() has run there is no session, so the status never arrives. Report first, quit in a finally.

Run it#

The project now has the shape every following chapter builds on:

src/test/java/com/example/
  RunCucumberTest.java
  pages/SignInPage.java
  steps/SignInSteps.java
  support/Browser.java  DriverFactory.java  Hooks.java
          Member.java   Field.java          ParameterTypes.java

mvn test -Dgrid=testingbot runs it on the grid exactly as before, and this time the dashboard shows each scenario as passed or failed. To check the failure path, try a scenario with a deliberately wrong expectation:

Scenario: Tom is wrongly expected to be rejected
  Given Tom has an account
  When Tom signs in with his password
  Then the sign-in is rejected because the password is invalid

It fails in Maven with Expected "Your password is invalid!" in "You logged into a secure area!", the HTML report holds a screenshot of the secure area, and the TestingBot session (269bcecb9b1f-d12cbadc881b-5a2db0fddb3e-179455810252-17429617) is marked as failed. Delete the scenario again afterwards.

Do not share state between scenarios#

Dependency injection shares state within a scenario. Between scenarios, nothing should be shared: every scenario must be able to run alone, in any order, on any thread. If a scenario needs a signed-in user, its Given signs one in (or creates one through an API); it does not rely on the scenario before it. Chapter 8 runs scenarios in parallel, which is the quickest way to find out whether you got this right.