Java – Selenium using 1 webdriver/browser for multiple test scenarios

In many cases you don’t want to start a browser for every test scenario. Ideally, you want to use the same resource for multiple test scenarios.

It is a no brainer, but how do you hold (reuse) the same browser/webdriver for multiple selenium test scenarios?

The simple answer is to make use of singleton pattern. See the example below:

import io.github.bonigarcia.wdm.ChromeDriverManager;
import org.openqa.selenium.chrome.ChromeDriver;

/**
* Created by TripleQA
*/
public class Browser {
  private static Browser instance = null;
  private static ChromeDriver chromeDriver;

  private Browser() {
  // Exists only to defeat instantiation.
  }

  public static Browser getInstance() {
    if(instance == null) {
     instance = new Browser();
     ChromeDriverManager.getInstance().setup();
     chromeDriver = new ChromeDriver();
    }
    return instance;
  }

  public  ChromeDriver getCurrentBrowser(){
    return chromeDriver;
  }

  public void close(){
    chromeDriver.quit();
    instance = null;
  }

}

Be aware that we are using the fabulous  ChromeDriverManager. However, the concept is simple. This singleton can now be used by a  Base testClass for example. See an example below:

import com.tripleqa.framework.test.utilities.Browser;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

/**
 * Created by TripleQA
 */
public class BasePage {
    public static ChromeDriver chromeDriver;
    public static final int PAGE_LOAD_TIMEOUT_SEC  = 10;
    public static final int IMPLICITLY_WAIT_SEC = 10;
    private static final String URL = "https://www.tripleqa.com";

    public BasePage() {
        Browser currentBrowser = Browser.getInstance();
        chromeDriver = currentBrowser.getCurrentBrowser();
        chromeDriver.manage().timeouts().pageLoadTimeout(PAGE_LOAD_TIMEOUT_SEC, TimeUnit.SECONDS);
        chromeDriver.manage().timeouts().implicitlyWait(IMPLICITLY_WAIT_SEC, TimeUnit.SECONDS);
        chromeDriver.get(URL);
    }

}

 

Every class that is inheriting the BaseClass can use the same webdriver. In that case it is tidy and reuse of resources.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s