Singleton Class in Cucumber Java
1. What is a Singleton Class?
A Singleton Class is a design pattern in Java that ensures only one instance of a class is created throughout the application.
In Selenium Cucumber automation frameworks, Singleton classes are useful for managing shared resources such as:
- WebDriver instances (with proper thread-safety considerations).
- Configuration properties.
- Test environment settings.
- Database connections.
- Framework utilities.
Main objective: Create a single instance of a class and provide a global access point to that instance.
2. How to Create a Singleton Class in Java
A Singleton class generally follows three rules:
- Create a private constructor to prevent object creation from outside the class.
- Create a private static variable to hold the class instance.
- Create a public static method to return the same instance.
Example: Basic Singleton Class
public class Singleton {
// Static instance
private static Singleton instance;
// Private constructor
private Singleton() {
System.out.println("Singleton instance created");
}
// Global access method
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void display() {
System.out.println("Singleton class method called");
}
}
Main Method
public class Main {
public static void main(String[] args) {
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
obj1.display();
System.out.println(obj1 == obj2);
}
}
Output:
Singleton instance created
Singleton class method called
true
Both objects refer to the same instance.
3. Singleton Class in Cucumber Selenium Java Framework
Let's understand how to use the Singleton design pattern in a Cucumber + Selenium + Java + TestNG framework.
Framework folder structure
CucumberFramework
│
├── src/test/java
│ │
│ ├── base
│ │ └── DriverManager.java
│ │
│ ├── stepdefinitions
│ │ └── LoginSteps.java
│ │
│ ├── hooks
│ │ └── Hooks.java
│ │
│ ├── runners
│ │ └── TestRunner.java
│ │
│ └── pages
│ └── LoginPage.java
│
└── pom.xml
4. Create Singleton DriverManager Class
We will create a Singleton class to manage the WebDriver instance.
DriverManager.java
package base;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class DriverManager {
private static DriverManager instance;
private WebDriver driver;
// Private constructor
private DriverManager() {
}
// Singleton instance
public static synchronized DriverManager getInstance() {
if (instance == null) {
instance = new DriverManager();
}
return instance;
}
// Initialize browser
public void initializeDriver() {
if (driver == null) {
driver = new ChromeDriver();
driver.manage().window().maximize();
}
}
// Get WebDriver
public WebDriver getDriver() {
return driver;
}
// Quit browser
public void quitDriver() {
if (driver != null) {
driver.quit();
driver = null;
}
}
}
Explanation:
private static DriverManager instance: Stores the Singleton instance.private DriverManager(): Prevents external object creation.getInstance(): Returns the same DriverManager object.initializeDriver(): Creates the Chrome browser.getDriver(): Returns the WebDriver instance.quitDriver(): Closes the browser and clears the reference.
5. Create Cucumber Hooks Class
Hooks are used to initialize and close the browser before and after each scenario.
Hooks.java
package hooks;
import base.DriverManager;
import io.cucumber.java.Before;
import io.cucumber.java.After;
public class Hooks {
@Before
public void setUp() {
DriverManager.getInstance().initializeDriver();
System.out.println("Browser launched");
}
@After
public void tearDown() {
DriverManager.getInstance().quitDriver();
System.out.println("Browser closed");
}
}
6. Create Login Step Definition
LoginSteps.java
package stepdefinitions;
import base.DriverManager;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;
public class LoginSteps {
@Given("User launches the application")
public void launchApplication() {
DriverManager.getInstance()
.getDriver()
.get("https://example.com");
}
@When("User gets the page title")
public void getPageTitle() {
String title = DriverManager.getInstance()
.getDriver()
.getTitle();
System.out.println("Page Title: " + title);
}
@Then("Application should be accessible")
public void verifyApplication() {
System.out.println("Application opened successfully");
}
}
7. Cucumber Feature File
login.feature
Feature: Login Functionality
Scenario: Verify application launch
Given User launches the application
When User gets the page title
Then Application should be accessible
8. How Singleton Works in Cucumber
Singleton execution flow
- Cucumber Test Execution
- DriverManager.getInstance() – Returns the same DriverManager object.
- initializeDriver() – Creates ChromeDriver.
- Step Definitions – Access WebDriver through DriverManager.
- After Hook – Quit browser and clear driver reference.
9. Thread Safety in Singleton Class
One important consideration is parallel execution.
The basic Singleton implementation using synchronized getInstance() ensures that only one DriverManager object is created, but it does not make the shared WebDriver safe for parallel Cucumber scenarios.
For parallel execution, use ThreadLocal to maintain a separate WebDriver instance for each thread.
Thread-safe DriverManager implementation
package base;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class DriverManager {
private static final DriverManager instance =
new DriverManager();
private final ThreadLocal<WebDriver> driver =
new ThreadLocal<>();
private DriverManager() {
}
public static DriverManager getInstance() {
return instance;
}
public void initializeDriver() {
if (driver.get() == null) {
WebDriver webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
driver.set(webDriver);
}
}
public WebDriver getDriver() {
return driver.get();
}
public void quitDriver() {
WebDriver webDriver = driver.get();
if (webDriver != null) {
webDriver.quit();
driver.remove();
}
}
}
Parallel execution example
ThreadLocal WebDriver architecture
- Thread 1: Scenario 1 → ChromeDriver 1.
- Thread 2: Scenario 2 → ChromeDriver 2.
One Singleton DriverManager: Maintains separate WebDriver references per thread.
10. Singleton vs Static Class
| Singleton Class | Static Class |
|---|---|
| Creates one instance | No object required |
| Supports interfaces | Cannot be instantiated or extended normally |
| Supports inheritance | Cannot be inherited |
| Can implement object-oriented design | Primarily provides static functionality |
| Can maintain instance state | Uses static state |
11. Advantages of Singleton in Automation Framework
- Avoids creating multiple manager objects.
- Provides centralized browser management.
- Improves resource management.
- Provides a common access point.
- Can support parallel execution when combined with ThreadLocal.
- Helps maintain consistent framework configuration.
12. Interview Questions
Q1. What is a Singleton design pattern?
A Singleton design pattern ensures that only one instance of a class is created and provides a global access point to that instance.
Q2. Why do we use Singleton in Selenium?
We use it to centralize the management of shared framework resources, such as configuration or driver management.
Q3. Is Singleton thread-safe by default?
No. A basic lazy Singleton implementation is not thread-safe. Synchronization, eager initialization, or an enum-based Singleton can address instance creation safety.
Q4. Can we use Singleton with Cucumber parallel execution?
Yes. However, a shared WebDriver field can cause conflicts. ThreadLocal should be used to maintain separate WebDriver instances for different scenario threads.
Q5. What is the difference between Singleton and ThreadLocal?
Singleton controls the number of instances of a class, whereas ThreadLocal provides a separate variable value for each thread.
Q6. Can we create a Singleton class using an enum?
Yes. Java enum provides a simple way to implement a Singleton with built-in protection against serialization and reflection-based instance duplication.
13. Best Practices
For a real-world Cucumber Selenium Java framework:
- Use Singleton for centralized framework managers when appropriate.
- Use ThreadLocal for WebDriver in parallel execution.
- Use Cucumber Scenario Context or dependency injection for scenario-specific data.
- Always quit the browser in the
@Afterhook. - Avoid sharing mutable scenario data between parallel scenarios.
- Avoid making every framework class a Singleton unnecessarily.
Interview takeaway: Singleton ensures one instance of a class, while ThreadLocal ensures each parallel execution thread has its own WebDriver. Combining these patterns is a common approach for building a parallel Cucumber Selenium automation framework.

No comments:
Post a Comment