Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebDriver instance created on @BeforeSuite level throws NullPointerException

I've been using TestNG to create my WebDriver tests and so far this combination has worked flawlessly. However I've been bumping into a problem so far that have not yet found a way to overcome.

WebDriver is created on the first test of a group that has over 950 tests spread through over 100 classes. In order to avoid creating multiple browsers instances (since most of the tests are pretty short and starting a browser takes sometimes longer than the test itself) i tried declaring the driver instance on a @BeforeSuite (and also destroying the object on a @AfterSuite) level on the first test and reuse it afterwards.

However once it starts on a different class, I've been bumping in a NullPointerException when it tries to find the driver.

The code is posted on gist on the following link (https://gist.github.com/4530030). The line that accuses the NullPointerException is SecondTest.java:15

like image 750
aimbire Avatar asked Dec 06 '25 02:12

aimbire


1 Answers

Probably this is a bit late, but your driver object is not being shared by firsttest and secondtest. Each of them have their own copies. So, whatever gets initialized is one's own copy. Whichever class would run first would work and the second class would not have it since it's copy is not initialized. What you can do is to have a class which returns the same driver object when asked for it..

public class DriverInitializer {

private static WebDriver driver;

@BeforeSuite
public void setTestSuite() throws MalformedURLException {
    driver = new FirefoxDriver();
}

@AfterSuite
public void endTestSuite() {
    driver.quit();
}

public static WebDriver getDriver(){
    return driver;
}

}

Then have all cases call eg. firstTest calls

DriverInitializer.getDriver().get("http://www.google.com");

Secondtest calls

DriverInitializer.getDriver().get("http://cnn.com");

So no matter who's calling the same driver instance would be returned.

The beforesuite and aftersuite need to be defined only once , they could be placed anywhere.just that in the above example they are referring to a private variable and hence i had to keep them in there..

like image 120
niharika_neo Avatar answered Dec 07 '25 17:12

niharika_neo