Saturday, December 2, 2017

How to reuse a browser session for tests using selenium?

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);
    driverBrowser
            .manage()
            .timeouts()
            .implicitlyWait(
                    Integer.valueOf(PropertyLoader
                            .loadProperty("implicit_timeout_sec")),
                    TimeUnit.SECONDS);
    driverBrowser.manage().window().maximize();
}
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:
  1. https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/3927
  2. https://sqa.stackexchange.com/questions/1988/selenium-reuse-existing-browser-session-instead-of-opening-new-windows

No comments:

Post a Comment