lapusan mirel lapusan mirel - 1 month ago 14
Java Question

Selenium java Browser session reuse

My question is as follows: How can I reuse a browser session for tests that are in different java classes? I have the browser open like this:

public class OpenBrowser {

public static WebDriver driver;

public static void openb() {
// Create a new instance of the Firefox driver
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Then I have to log into a website using some credentials and after it's logged I want to perform other tests, I do not want to log in for every test because there are a lot of them that I need to make and logging in for each will take a decade. For example a flow looks like : Log In->Push some component->add some values->Generate a report. Than after this i would like to generate other report on another component but when I try to it gives a null pointer exception. Any ideas? :)


In Selenium 2 with WebDriver you can call

driver = new FirefoxDriver();

which spawns a browser, and that browser will stay open for the duration of your testing,

or you can choose to close it with driver.Quit().

Actually what I want to do?

I like to close my browser window between tests so that I know my tests aren't "dirty" with stored session data that could affect how the tests run, but I can see value in some targeted tests, where I want to try a couple different scenarios while keeping the same session going.

For code level: you can check is it null or not. If null then call the browser to give another.

 * Driver for web application.
 * @return driver Browser
 * @throws IOException
public WebDriver getDriverBrowser() throws IOException {

if (driverBrowser == null) {
    String sBrowser = PropertyLoader.loadProperty("browser");
    driverBrowser = getBrowser(sBrowser);
return driverBrowser;

Or you can use xml configuration to use some test cases as class level or test specific.Using TestNG, you can specify which tests you want to run (TestNG will generate an XML file of all of the tests that fail, so when you run it, it will only execute the failed tests).

Issue - 1: I mean i don't want to log in again to continue testing , I don't mind if it opens another window, in fact as you said it's more reliable but not helpful if i have to log in again.

If you don't want to login, then in every testcase, you need a base starting point. After ending any test case, it will go to base position and next testcase will start from the base

Issue - 2: How can i implement a base starting point?

It is up to you. First you have to analyze the test cases, then you have to select which point can be the starting point for all or set of some test cases. Then you can do it.

For more: