Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cucumber + Selenium Java : keep the browser open between test cases

Tags:

java

selenium

I'm currently using Cucumber and Selenium WebDriver in Java to test a web application. I'm not very happy with the fact that the browser is closed and reopened between each test cases.

First, it's pretty slow and in addition, it makes no sense to me.

What I want to do is to log off the app between each tests and keep the browser open.

I thought that this line could do the work, but it doesn't work as expected :

driver.navigate().to("http://myurl.url");

Instead of :

driver.get("http://myurl.url");

It opens a new browser. I understand why it does this, but I want to attach to my previous session of my browser.

like image 381
Nicolas G. Duvivier Avatar asked Mar 15 '23 11:03

Nicolas G. Duvivier


1 Answers

I found a way to keep my browser open between tests. I used the Singleton Design Pattern with picocontainer. I declare my browser in static in this class.

public class Drivers {
    private static boolean initialized = false;
    private static WebDriver driver;

    @Before
    public void initialize(){
        if (!initialized){
            initialized = true;
            driver = new FirefoxDriver();
            driver.get("http://myurl.url");
        }
    }
    public static WebDriver getDriver(){
        return driver;
    }   
}

In each StepDefinitions class, I have a constructor that instantiates my Singleton.

public class DashboardSteps extends SuperSteps {
    Drivers context;

    @After
    public void close(Scenario scenario) {
        super.tearDown(scenario);
        loginPage = homePage.clickLogout();
        loginPage.waitPageLoaded();
    }

    public DashboardSteps(Drivers context) {
        super(context);
    }

The SuperSteps class :

public class SuperSteps {
    protected Drivers context;

    public SuperSteps(Drivers context){
        this.context = context;
    }

As you can see, I go back to the logIn Page after each test, so I can run every tests independently.

like image 126
Nicolas G. Duvivier Avatar answered Mar 17 '23 00:03

Nicolas G. Duvivier