Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Page Objects and UI Tests

Selenium with Cucumber: Setup and Driver Lifecycle

Wire Cucumber to Selenium: Maven dependencies, the JUnit Platform runner, a driver factory, per-scenario browser start and quit, headless options and failure screenshots.

Cucumber does not drive browsers. It reads Gherkin and calls your Java methods. A browser enters the picture only when one of those methods uses a tool such as Selenium WebDriver or Playwright. This lesson shows the standard way to connect them: the dependencies, the runner, a small driver factory, hooks that start and stop the browser for each scenario, and a screenshot on failure.

Neither Cucumber nor a browser can run on this site, so the real configuration is read-only. The runnable part is a stand-in for the driver lifecycle: it shows why a per-thread holder and tagged hooks are the right design, using only plain Java.

Dependencies

With Maven, a typical pom.xml for a Selenium suite (use the current versions from Maven Central when you start) contains:

XML
<dependencies>
  <dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>${cucumber.version}</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit-platform-engine</artifactId>
    <version>${cucumber.version}</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-picocontainer</artifactId>
    <version>${cucumber.version}</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-suite</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>${selenium.version}</version>
    <scope>test</scope>
  </dependency>
</dependencies>

Selenium 4 includes Selenium Manager, which downloads a matching browser driver automatically, so you no longer manage chromedriver files by hand.

The runner

With the JUnit Platform engine, a tiny suite class tells JUnit to use Cucumber, where the features are and which packages hold glue code:

Java
package shop;

import org.junit.platform.suite.api.*;
import static io.cucumber.junit.platform.engine.Constants.*;

@Suite
@IncludeEngines("cucumber")
@SelectClasspathResource("features")
@ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "shop.steps")
@ConfigurationParameter(key = PLUGIN_PROPERTY_NAME,
        value = "pretty, html:target/cucumber.html")
public class RunCucumberTest { }

Features live in src/test/resources/features, glue code in src/test/java/shop/steps. Reports are covered in Reports and plugins.

A driver holder

Page objects need a driver, and hooks need to create and destroy it. Put it in an injectable class with one instance per scenario (see Scenario state and DI):

Java
public class Browser {
    private WebDriver driver;

    public WebDriver driver() {
        if (driver == null) {
            ChromeOptions options = new ChromeOptions();
            if (Boolean.getBoolean("headless")) {
                options.addArguments("--headless=new", "--window-size=1280,900");
            }
            driver = new ChromeDriver(options);
        }
        return driver;
    }

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

Creating the driver lazily, on first use, means a scenario that never touches the browser never starts one. Pass -Dheadless=true on CI, where no screen exists.

The hooks

Java
public class WebHooks {
    private final Browser browser;

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

    @Before("@web")
    public void start() {
        browser.driver().manage().window().setSize(new Dimension(1280, 900));
    }

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

    @After("@web")
    public void stop() {
        browser.quit();
    }
}

Several choices matter here:

  • The hooks carry the @web tag, so API-only scenarios do not pay for a browser (Tags).
  • quit() is safe to call twice, because @After runs even when setup failed (Hooks).
  • The screenshot is attached to the report so you see the failing page without reproducing the run.
  • A fresh browser per scenario is slow but isolated. Reusing one browser across scenarios is faster, but then you must clear cookies and storage in @Before, and a crashed browser takes later scenarios with it.

Choosing browsers

Read the browser name from a system property so CI can switch without code changes:

Java
String name = System.getProperty("browser", "chrome");
WebDriver driver = switch (name) {
    case "firefox" -> new FirefoxDriver();
    case "edge"    -> new EdgeDriver();
    default        -> new ChromeDriver();
};

For a grid or cloud provider, replace the constructor with new RemoteWebDriver(new URL(gridUrl), options). Page objects need no change, since they only see WebDriver.

A runnable stand-in for the lifecycle

This program fakes a browser with a counter of "open windows", and shows that only @web scenarios start one, that quit runs even when a step fails, and that a failure triggers a screenshot attachment.

Java Driver lifecycle with tags (Java stand-in)

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.

The count returns to zero after every scenario, including the failed one. In a real suite, the same discipline stops browsers piling up and exhausting memory on the build server.

Practical tips

  • Never share a WebDriver between threads; give each scenario its own, or use a ThreadLocal. See Parallel execution.
  • Set an explicit window size, so layouts (and screenshots) are the same on every machine.
  • Keep base URLs and credentials in configuration (-Dbase.url=... or environment variables), never in step text.
  • Prefer testing UI behavior that really needs a browser. Calculations, rules and API behavior are better covered with fast non-UI scenarios; see API and service-layer tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which component actually opens the browser in a Cucumber and Selenium suite?

    Cucumber only calls your methods. The browser is started by your code through WebDriver.
  2. 2. Why create the driver lazily and attach the hooks to @web?

    Lazy creation and tagged hooks keep fast, non-UI scenarios fast.
  3. 3. What is Selenium Manager?

    It removes the need to download and point to chromedriver manually.
  4. 4. Why should quit() be safe to call twice or when no driver exists?

    An After hook can run when the Before hook never created the driver, so cleanup must be defensive.

Summary

  • Cucumber calls Java; Selenium drives the browser; add cucumber-java, a JUnit Platform runner and selenium-java.
  • Hold the driver in an injectable class, create it lazily and quit it in @After.
  • Use @web-tagged hooks, headless mode on CI and screenshot attachments for failures.
  • Never share a driver across threads, and keep URLs and credentials in configuration.

Next: Component objects and waits