Handling WebDriver Instance Across Multiple Step Definition Files in Cucumber + TestNG + Java
When you have multiple feature files and multiple step definition classes, you should use a centralized DriverFactory with ThreadLocal WebDriver.
You should not create a new WebDriver in every step definition class.
Instead:
- Create WebDriver in one centralized
DriverFactory. - Initialize it in Cucumber
@Beforehook. - Access the same WebDriver from any step definition class using
DriverFactory.getDriver(). - Close it in the Cucumber
@Afterhook. - Use
ThreadLocalto isolate browser instances during parallel execution.
1. Project Structure
src/test/java
│
├── factory
│ └── DriverFactory.java
│
├── hooks
│ └── Hooks.java
│
├── stepdefinitions
│ ├── LoginSteps.java
│ ├── HomeSteps.java
│ ├── ProfileSteps.java
│ └── LogoutSteps.java
│
├── runners
│ └── TestRunner.java
│
└── pages
├── LoginPage.java
├── HomePage.java
└── ProfilePage.java
src/test/resources
│
└── features
├── login.feature
├── home.feature
└── profile.feature
2. Create Centralized DriverFactory
DriverFactory.java
package factory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class DriverFactory {
private static final ThreadLocal<WebDriver> driver =
new ThreadLocal<>();
public static void initDriver() {
WebDriver webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
driver.set(webDriver);
}
public static WebDriver getDriver() {
return driver.get();
}
public static void quitDriver() {
if (driver.get() != null) {
driver.get().quit();
driver.remove();
}
}
}
Important: ThreadLocal maintains a separate WebDriver instance for each execution thread.
3. Initialize WebDriver in Hooks
Hooks.java
package hooks;
import factory.DriverFactory;
import io.cucumber.java.Before;
import io.cucumber.java.After;
public class Hooks {
@Before
public void beforeScenario() {
DriverFactory.initDriver();
System.out.println(
"Browser Started: " +
Thread.currentThread().getId()
);
}
@After
public void afterScenario() {
System.out.println(
"Browser Closed: " +
Thread.currentThread().getId()
);
DriverFactory.quitDriver();
}
}
The browser is initialized once per scenario, not once per step definition file.
4. Access the Same WebDriver in LoginSteps.java
package stepdefinitions;
import factory.DriverFactory;
import org.openqa.selenium.WebDriver;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
public class LoginSteps {
WebDriver driver;
@Given("user opens login page")
public void openLoginPage() {
driver = DriverFactory.getDriver();
driver.get("https://www.saucedemo.com/");
}
@When("user enters username")
public void enterUsername() {
driver = DriverFactory.getDriver();
driver.findElement(
org.openqa.selenium.By.id("user-name")
).sendKeys("standard_user");
}
}
5. Access the Same WebDriver in HomeSteps.java
package stepdefinitions;
import factory.DriverFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import io.cucumber.java.en.Then;
import org.testng.Assert;
public class HomeSteps {
WebDriver driver;
@Then("user should see home page")
public void verifyHomePage() {
driver = DriverFactory.getDriver();
Assert.assertTrue(
driver.findElement(By.className("inventory_list"))
.isDisplayed()
);
}
}
6. Access the Same WebDriver in ProfileSteps.java
package stepdefinitions;
import factory.DriverFactory;
import org.openqa.selenium.WebDriver;
import io.cucumber.java.en.When;
public class ProfileSteps {
WebDriver driver;
@When("user navigates to profile")
public void navigateToProfile() {
driver = DriverFactory.getDriver();
driver.get("https://example.com/profile");
}
}
Notice: All three step definition classes use DriverFactory.getDriver().
They receive the same browser instance when they execute within the same scenario and thread.
7. How Multiple Step Definition Files Share WebDriver
Suppose your feature file contains steps implemented in different Java classes.
login.feature
Feature: User Login
Scenario: Login and verify home page
Given user opens login page
When user enters username
Then user should see home page
Execution Flow
- Cucumber Scenario: Executes the scenario from
login.feature. - Hooks.java: Creates the WebDriver instance.
- DriverFactory: Stores the WebDriver in ThreadLocal.
- LoginSteps: Accesses the browser using
getDriver(). - HomeSteps: Accesses the same browser using
getDriver(). - ProfileSteps: Can also access the same browser using
getDriver(). - After Hook: Quits the browser and removes the ThreadLocal value.
Result: All step definition classes operate on the same browser instance within a scenario.
8. What Happens During Parallel Execution?
Suppose two scenarios execute simultaneously.
| Component | Thread 1 | Thread 2 |
|---|---|---|
| Scenario | Login scenario | Profile scenario |
| DriverFactory | ThreadLocal | ThreadLocal |
| Browser | Chrome 1 | Chrome 2 |
| LoginSteps | Driver 1 | Driver 2 |
| HomeSteps | Driver 1 | Driver 2 |
| ProfileSteps | Driver 1 | Driver 2 |
Each thread gets its own browser instance.
Step definition classes access the correct browser through the current thread.
9. Alternative: Using Constructor Dependency Injection
For a larger Cucumber framework, you can also use dependency injection with PicoContainer.
Instead of calling DriverFactory.getDriver() in every step definition, create a shared scenario-level TestContext object.
TestContext.java
package context;
import org.openqa.selenium.WebDriver;
public class TestContext {
private WebDriver driver;
public void setDriver(WebDriver driver) {
this.driver = driver;
}
public WebDriver getDriver() {
return driver;
}
}
Hooks.java
package hooks;
import context.TestContext;
import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.Before;
import io.cucumber.java.After;
public class Hooks {
private final TestContext context;
public Hooks(TestContext context) {
this.context = context;
}
@Before
public void setup() {
context.setDriver(new ChromeDriver());
context.getDriver()
.manage()
.window()
.maximize();
}
@After
public void tearDown() {
if (context.getDriver() != null) {
context.getDriver().quit();
}
}
}
LoginSteps.java
package stepdefinitions;
import context.TestContext;
import io.cucumber.java.en.Given;
public class LoginSteps {
private final TestContext context;
public LoginSteps(TestContext context) {
this.context = context;
}
@Given("user opens login page")
public void openLoginPage() {
context.getDriver()
.get("https://www.saucedemo.com/");
}
}
HomeSteps.java
package stepdefinitions;
import context.TestContext;
import io.cucumber.java.en.Then;
public class HomeSteps {
private final TestContext context;
public HomeSteps(TestContext context) {
this.context = context;
}
@Then("user verifies home page")
public void verifyHomePage() {
System.out.println(
context.getDriver().getTitle()
);
}
}
Add PicoContainer Dependency
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>7.20.1</version>
<scope>test</scope>
</dependency>
With PicoContainer, objects are shared within a scenario and isolated between scenarios.
10. Which Approach Should You Use?
| Approach | Advantages | Recommended For |
|---|---|---|
| ThreadLocal DriverFactory | Simple and easy to implement | Small and medium frameworks |
| PicoContainer + TestContext | Scenario-level dependency injection and clean architecture | Large frameworks |
| Static WebDriver | Easy to access but unsafe for parallel execution | Avoid |
Recommendation: For a professional Cucumber + TestNG + Selenium framework, I recommend PicoContainer + TestContext + Page Object Model.
It gives you:
- One WebDriver per scenario.
- Same WebDriver across multiple step definition classes.
- Independent browser instances during parallel execution.
- No need to repeatedly call a static DriverFactory.
- Better separation of hooks, context, step definitions and page objects.
Important: Do not combine the PicoContainer scenario context approach with a second independent WebDriver lifecycle in DriverFactory. Choose one ownership strategy to avoid accidentally creating two browser instances per scenario.

No comments:
Post a Comment