Latest post from this blog
Singleton in Selenium Framework
- Get link
- X
- Other Apps
๐ก What Is Singleton?
The Singleton Design Pattern means creating only one object (instance) of a class and reusing it wherever needed.
In Selenium automation, we use Singleton to make sure that only one WebDriver instance is created and used throughout the test execution.
⚙️ Why We Need Singleton in Selenium
If we create multiple WebDriver instances in the same test run:
-
๐ช Multiple browser windows may open unnecessarily
-
๐ Browser sessions may conflict
-
⚠️ Tests may fail or behave unexpectedly
๐ The Singleton pattern prevents this by allowing only one WebDriver instance to exist at a time.
๐งฉ How Singleton Works
1️⃣ The constructor is private, so no one can create objects directly.
2️⃣ A static method provides access to the single instance.
3️⃣ The same instance is reused wherever it’s needed.
๐งฑ Example: Singleton WebDriver Manager
package driver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class DriverSingleton {
// Step 1: Create a private static instance variable
private static WebDriver driver;
// Step 2: Make the constructor private
private DriverSingleton() { }
// Step 3: Provide a public static method to get the driver instance
public static WebDriver getDriver() {
if (driver == null) {
driver = new ChromeDriver();
driver.manage().window().maximize();
}
return driver;
}
// Step 4: Quit the driver and reset it to null
public static void quitDriver() {
if (driver != null) {
driver.quit();
driver = null;
}
}
}
✅ How to Use It
public class TestExample {
public static void main(String[] args) {
// Get the same WebDriver instance
WebDriver driver = DriverSingleton.getDriver();
driver.get("https://example.com");
System.out.println(driver.getTitle());
// Close the browser
DriverSingleton.quitDriver();
}
}
๐ Benefits of Using Singleton
✅ Only one browser instance per test run
✅ Easy to manage WebDriver lifecycle
✅ Saves memory and resources
✅ Reduces code duplication
⚠️ Limitations
❌ Not suitable for parallel testing (multiple threads need separate driver instances)
๐ In that case, use ThreadLocal for thread safety — You can refer below link to the detailed explanation here: https://softwaretestingbugblab.blogspot.com/2025/10/ensuring-thread-safety-in-parallel-test.html
๐งพ In Short:
The Singleton Design Pattern in Selenium ensures that only one WebDriver instance is created and reused across the entire test execution — making your framework cleaner, efficient, and easy to maintain.
Comments
Post a Comment