Cucumber Hooks

Last Updated : 12 Aug, 2025

Cucumber Hooks are special methods that automatically run before and after each scenario, feature, or step in your tests. They are defined using Cucumber annotations such as @Before and @After.

Hooks help to manage repetitive tasks like:

  • Initialize WebDriver before tests.
  • Clean up resources after tests.
  • Set up test data or environment configurations.
  • Capture screenshots of test failures.
  • Generate reports and logs for better tracking.

Example of Hooks in Cucumber

Step 1. Create a Maven project and add the required dependencies to it.

Cucumber-Hooks-Structure
Cucumber Hooks Structure

Pom.xml

XML
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.geeks</groupId>
  <artifactId>CucumberHooks</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <!-- Cucumber Java Dependency -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.10.0</version> <!-- Updated version -->
        <scope>test</scope>
    </dependency>

    <!-- Cucumber TestNG Dependency -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-testng</artifactId>
        <version>7.10.0</version> <!-- Updated version -->
        <scope>test</scope>
    </dependency>

    <!-- Selenium WebDriver Dependency -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
        <scope>test</scope>
    </dependency>

    <!-- TestNG Dependency -->
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.3.0</version>
        <scope>test</scope>
    </dependency>

    <!-- Cucumber Picocontainer Dependency for Dependency Injection -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-picocontainer</artifactId>
        <version>7.10.0</version> <!-- Updated version -->
        <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
        </plugin>
    </plugins>
  </build>
</project>


Step 2. In src/test/resources folder, create a feature file that describes the login functionality using Gherkin syntax:

login.feature

feature
Feature: User Login

  @LoginTest
  Scenario: User logs in with valid credentials
    Given the user is on the login page
    When the user enters "standard_user" and "secret_sauce"
    Then the user should be redirected to the homepage

@LoginTest: This tag is used to associate specific @Before and @After hooks with a particular scenario. Given, When, Then these are the step keywords used in Cucumber to define the flow of your scenario.

Step 3. Create the step definitions file are the methods that execute the actual steps from the feature file.

LoginSteps.java

Java
package stepdefinitions;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;

public class LoginSteps {

    private WebDriver driver;

    // Constructor to inject WebDriver from Hooks class
    public LoginSteps(Hooks hooks) {
        this.driver = hooks.driver;
    }

    @Given("the user is on the login page")
    public void userOnLoginPage() {
        driver.get("https://www.saucedemo.com/");
    }

    @When("the user enters {string} and {string}")
    public void userEntersCredentials(String username, String password) {
        WebElement usernameField = driver.findElement(By.id("user-name"));
        WebElement passwordField = driver.findElement(By.id("password"));
        WebElement loginButton = driver.findElement(By.id("login-button"));

        usernameField.sendKeys(username);
        passwordField.sendKeys(password);
        loginButton.click();
    }

    @Then("the user should be redirected to the homepage")
    public void userRedirectedToHomepage() {
        String currentUrl = driver.getCurrentUrl();
        assert currentUrl.contains("inventory.html");
    }
}

Constructor Injection In this approach, the WebDriver instance is injected into the step definition class through the constructor. Step Methods define the actions performed during the test. They correspond to the Given, When, and Then steps in the feature file.

Step 4. Create Hooks class is where we initialize the WebDriver before each scenario and close it after each scenario.

Hooks.java

Java
package stepdefinitions;

import io.cucumber.java.Before;
import io.cucumber.java.After;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Hooks {

    // WebDriver instance shared across all step definitions
    public WebDriver driver;

    // Initialize WebDriver before each scenario
    @Before("@LoginTest")
    public void setup() {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Change the path of the chromedriver\\drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        System.out.println("Browser initialized for Login Test");
    }

    // Clean up WebDriver after each scenario
    @After("@LoginTest")
    public void teardown() {
        if (driver != null) {
            driver.quit();
            System.out.println("Browser closed after Login Test");
        }
    }
}

In @Before WebDriver is initialized before the scenario starts, allowing you to set up the browser and prepare the test environment. And in @After WebDriver is closed after the scenario ends.

Step 5. Create Test Runner class to execute the Cucumber feature files with TestNG.

TestRunner.java

Java
package testrunner;

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;

@CucumberOptions(
    features = "src/test/resources/login.feature", // Path to the feature file
    glue = "stepdefinitions",  // Package for step definitions and hooks
    plugin = {"pretty", "html:target/cucumber-reports"}  // Optional: Generate reports
)
public class TestRunner extends AbstractTestNGCucumberTests {
}


@CucumberOptions this annotation is used to configure the Cucumber test runner. The TestRunner class extends AbstractTestNGCucumberTests to integrate TestNG with Cucumber.

Step 6. Run the TestRunner class as a TestNG test.

output-of-Cucumber-Hooks
output of Cucumber Hooks


Comment
Article Tags:

Explore