RE: How to pass single browser instance to different classes

How to pass single browser instance to different classes ,
Say Ex : I have Class A where i initialize browser and steps of test will be spread across different method defined in different class say Class B , Class C . But my Actual test method is written in Class D .

Here how can i use single instance , Because i can see null value in driver in subClasses .
Please do let me know if more Info required .

Add Comment
5 Answers

There are multiple ways to do this.

1. To every class pass the webdriver instance. As webdriver is a reference type you will just copy the address and your webdriver will be an updated version throughout.
2. Isolate the browser creation logic from Tests. Create a seperate class, lets say, BrowserFactory and in that class create a WebDriver object.  Call this class every time you want a webdriver instance. This mechanism when implemented properly is called a Factory design pattern,  Just take a look at factory pattern theory and create a class for that.

Sample code will look something like this, you may want to improvise on this as per your needs

package Factories;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;


import org.openqa.selenium.firefox.FirefoxDriver;


* This class has following responsibilities

* - To create required WebDriver

* - To maintain an instance of a WebDriver


public class BrowserFactory {
private static WebDriver driver;
public static WebDriver getBrowser(String browserName) {

if (driver == null) {

if (browserName.equals("Firefox")) {
driver = new FirefoxDriver();

} else if (browserName.equals("InternetExplorer")) {

driver = new InternetExplorerDriver();

} else if (browserName.equals("Chrome")) {

System.setProperty("", DataProviderFactory


driver = new ChromeDriver();

long pageLoadTimeOut = DataProviderFactory


long implictWait = DataProviderFactory.getRunConfigDataProvider()



.pageLoadTimeout(pageLoadTimeOut, TimeUnit.MILLISECONDS);


.implicitlyWait(implictWait, TimeUnit.MILLISECONDS);


return driver;

public static WebDriver getBrowser() {

return driver;

public static void closeWebDriver() {



driver = null;



Professor Answered on June 2, 2015.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.