Saturday, December 5, 2026

Cucumber Hooks in Selenium Java (TestNG)

Cucumber Hooks in Selenium Java (TestNG)

In Cucumber, Hooks are special methods that execute before and after each scenario. They are used to perform preconditions and postconditions, such as launching the browser, initializing WebDriver, taking screenshots, closing the browser, and generating test reports.

When using Selenium WebDriver with Java, Cucumber hooks help manage browser initialization and cleanup without writing the same code in every step definition.

Cucumber Hooks in Selenium Java (TestNG)


1. Types of Cucumber Hooks

Cucumber provides the following commonly used hooks:

Hook Execution
@BeforeBefore every scenario
@AfterAfter every scenario
@BeforeStepBefore every step
@AfterStepAfter every step
@BeforeAllOnce before all scenarios
@AfterAllOnce after all scenarios

Note: @BeforeAll and @AfterAll are Cucumber Java hooks and are different from TestNG annotations.

2. Project Structure

A typical Cucumber Selenium Java project structure:

CucumberSeleniumProject
│
├── src/test/java
│   │
│   ├── runners
│   │   └── TestRunner.java
│   │
│   ├── stepdefinitions
│   │   └── LoginSteps.java
│   │
│   ├── hooks
│   │   └── Hooks.java
│   │
│   └── utilities
│       └── DriverFactory.java
│
├── src/test/resources
│   └── features
│       └── Login.feature
│
└── pom.xml

3. Maven Dependencies

Add the following dependencies to your pom.xml.

<dependencies>

    <!-- Selenium -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.27.0</version>
    </dependency>

    <!-- Cucumber Java -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.20.1</version>
        <scope>test</scope>
    </dependency>

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

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

</dependencies>

These are example pinned versions; use compatible current versions when setting up a new project.

4. Create DriverFactory.java

Create a reusable WebDriver factory class to initialize and manage browser instances.

DriverFactory.java

package utilities;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class DriverFactory {

    private static ThreadLocal<WebDriver> driver =
            new ThreadLocal<>();

    public static void initDriver() {

        driver.set(new ChromeDriver());

        getDriver().manage().window().maximize();
    }

    public static WebDriver getDriver() {
        return driver.get();
    }

    public static void quitDriver() {

        if (driver.get() != null) {
            driver.get().quit();
            driver.remove();
        }
    }
}

Why use ThreadLocal?

  • Supports parallel scenario execution.
  • Each scenario thread gets its own WebDriver instance.
  • Prevents multiple scenarios from sharing the same browser instance.
  • Helps avoid WebDriver conflicts during parallel execution.

5. Create Hooks.java

This is the most important class for managing browser setup and teardown.

Hooks.java

package hooks;

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

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

import utilities.DriverFactory;

public class Hooks {

    @Before
    public void beforeScenario(Scenario scenario) {

        System.out.println("Starting Scenario: "
                + scenario.getName());

        // Launch browser
        DriverFactory.initDriver();

        // Navigate to application
        DriverFactory.getDriver()
                .get("https://www.google.com");
    }

    @After
    public void afterScenario(Scenario scenario) {

        System.out.println("Finished Scenario: "
                + scenario.getName());

        // Capture screenshot if scenario fails
        if (scenario.isFailed()) {

            byte[] screenshot = ((TakesScreenshot)
                    DriverFactory.getDriver())
                    .getScreenshotAs(OutputType.BYTES);

            scenario.attach(
                    screenshot,
                    "image/png",
                    "Failed Scenario Screenshot"
            );
        }

        // Close browser
        DriverFactory.quitDriver();
    }
}

Explanation:

  • @Before: Executes before each scenario.
  • @After: Executes after each scenario.
  • Scenario: Provides scenario information.
  • scenario.isFailed(): Checks whether the scenario failed.
  • scenario.attach(): Attaches screenshots to the Cucumber report.
  • quitDriver(): Closes the browser and removes the ThreadLocal instance.

6. Create Login.feature

Feature: Login functionality

  Scenario: Verify successful login
    Given user launches the application
    When user enters username and password
    Then user should be able to login

  Scenario: Verify invalid login
    Given user launches the application
    When user enters invalid credentials
    Then login should fail

7. Create LoginSteps.java

package stepdefinitions;

import io.cucumber.java.en.*;

import utilities.DriverFactory;

import org.openqa.selenium.By;

public class LoginSteps {

    @Given("user launches the application")
    public void launchApplication() {

        DriverFactory.getDriver()
                .get("https://example.com");
    }

    @When("user enters username and password")
    public void enterCredentials() {

        DriverFactory.getDriver()
                .findElement(By.id("username"))
                .sendKeys("admin");

        DriverFactory.getDriver()
                .findElement(By.id("password"))
                .sendKeys("admin123");
    }

    @Then("user should be able to login")
    public void verifyLogin() {

        System.out.println("Login successful");
    }

    @When("user enters invalid credentials")
    public void enterInvalidCredentials() {

        System.out.println("Entering invalid credentials");
    }

    @Then("login should fail")
    public void verifyFailedLogin() {

        System.out.println("Login failed as expected");
    }
}

The example URLs and locators are placeholders. Replace them with your application's actual login page and elements.

8. Cucumber Hooks with Order

You can define multiple @Before and @After hooks and control their execution order.

@Before(order = 1)
public void launchBrowser() {
    System.out.println("Launch Browser");
}

@Before(order = 2)
public void setupTestData() {
    System.out.println("Setup Test Data");
}

@After(order = 1)
public void closeBrowser() {
    System.out.println("Close Browser");
}

@After(order = 2)
public void cleanupTestData() {
    System.out.println("Cleanup Test Data");
}

Execution order:

Before hooks

  1. Launch Browser (order 1)
  2. Setup Test Data (order 2)

Scenario execution

Execute Given, When, Then steps.

After hooks

  1. Cleanup Test Data (order 2)
  2. Close Browser (order 1)

Important: @Before hooks execute in ascending order, whereas @After hooks execute in descending order.

9. Conditional Hooks using Tags

Cucumber supports conditional hooks using tags.

Example feature file:

@smoke
Scenario: Verify login
    Given user launches the application

@regression
Scenario: Verify search functionality
    Given user launches the application

Hooks implementation:

@Before("@smoke")
public void smokeSetup() {
    System.out.println("Smoke test setup");
}

@Before("@regression")
public void regressionSetup() {
    System.out.println("Regression test setup");
}

@After("@smoke")
public void smokeTeardown() {
    System.out.println("Smoke test cleanup");
}

Only scenarios matching the specified tag execute the corresponding hook.

10. BeforeStep and AfterStep Hooks

These hooks execute before and after every individual scenario step.

@BeforeStep
public void beforeStep() {
    System.out.println("Before Step Execution");
}

@AfterStep
public void afterStep() {
    System.out.println("After Step Execution");
}

Use cases:

  • Logging each step.
  • Capturing screenshots after steps.
  • Debugging test failures.
  • Tracking step execution time.

Avoid taking screenshots after every step unless required, as it can increase execution time.

11. BeforeAll and AfterAll Hooks

These hooks execute once for the entire Cucumber test run.

import io.cucumber.java.BeforeAll;
import io.cucumber.java.AfterAll;

public class Hooks {

    @BeforeAll
    public static void beforeAll() {
        System.out.println("Execution Started");
    }

    @AfterAll
    public static void afterAll() {
        System.out.println("Execution Completed");
    }
}

Typical use cases:

  • Initialize global test configuration.
  • Start a mock server.
  • Initialize shared test infrastructure.
  • Perform global cleanup.

Avoid sharing a single WebDriver across parallel scenarios.

12. TestRunner.java

Configure Cucumber with TestNG.

package runners;

import org.testng.annotations.DataProvider;

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

@CucumberOptions(
    features = "src/test/resources/features",
    glue = {
        "stepdefinitions",
        "hooks"
    },
    plugin = {
        "pretty",
        "html:target/cucumber-reports.html",
        "json:target/cucumber.json"
    },
    monochrome = true
)

public class TestRunner extends AbstractTestNGCucumberTests {

    @Override
    @DataProvider(parallel = true)
    public Object[][] scenarios() {
        return super.scenarios();
    }
}

Set parallel = false if you want sequential execution.

13. Execution Flow

  1. TestNG Test Runner
  2. Cucumber Before Hook
  3. Initialize Selenium WebDriver
  4. Execute Feature File Steps
  5. Cucumber After Hook
  6. Screenshot if Failed + Quit Browser

14. Important Cucumber Hooks Interview Questions

Q1. What is the difference between Hooks and Background in Cucumber?

Hooks Background
Written in Java Written in feature file
Used for browser setup and teardown Used for common business steps
Executes outside feature steps Executes before each scenario in a feature
Can be conditional using tags Cannot replace Java setup logic

Q2. Can we have multiple Before hooks?

Yes. You can define multiple @Before hooks and control execution using the order parameter.

Q3. Can we execute hooks for specific scenarios?

Yes. Use conditional hooks with tags, such as @Before("@smoke").

Q4. Can we take screenshots only when a scenario fails?

Yes. Use scenario.isFailed() inside the @After hook.

Q5. What happens if a step fails?

Cucumber skips the remaining steps in that scenario and executes the applicable @After hooks.

Q6. Can we run Cucumber hooks in parallel execution?

Yes. Hooks execute independently for parallel scenarios. Use ThreadLocal WebDriver management to prevent browser sharing.

Q7. What is the difference between @Before and @BeforeAll?

  • @Before: Executes before every scenario.
  • @BeforeAll: Executes once before all scenarios.

Best practices for a real-world automation framework

  1. Keep browser initialization inside a reusable DriverFactory.
  2. Use ThreadLocal for parallel execution.
  3. Capture screenshots only for failed scenarios.
  4. Keep hooks separate from step definitions.
  5. Use tags for environment-specific or scenario-specific setup.
  6. Use dependency injection or a shared scenario context when multiple classes need to share test data.
  7. Always close WebDriver in teardown, even when screenshot capture fails.

Recommended framework architecture: Cucumber + Selenium 4 + Java + TestNG + Maven + ExtentReports + Page Object Model + ThreadLocal WebDriver.

No comments:

Post a Comment