Here is my code:
public class BasePage extends PageObject {
@Managed
WebDriver driver;
public Alert waitingForAlert() throws InterruptedException {
Alert al = driver.switchTo().alert();
return al;
}
I'm getting the error
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.switchTo()" because "this.driver" is null
CodePudding user response:
You get this error only because of using driver before creating an instance of it. Let's suppose you want to run this test case on Chrome and your PageObject class doesn't have Chrome Driver instance (if yes it will create new chrome driver instance again which is not supposed to do)
WebDriver driver;
public Alert waitingForAlert() throws InterruptedException {
Alert al = driver.switchTo().alert();
return al;
}
The nullPointer exception comes from this line: driver.switchTo().alert();
in order to use driver you should create an instance of it. Meaning you can do it by typing:
class BasePage extends PageObject {
@Managed
WebDriver driver;
public void setDriver()
{
System.setProperty("webdriver.chrome.driver","<Path of ChromeDriver.exe here>");
driver = new ChromeDriver(); // Creating new 'ChromeDriver' instance
}
public Alert waitingForAlert() throws InterruptedException {
setDriver();
Alert al = driver.switchTo().alert();
return al;
}
}
CodePudding user response:
What you're seeing is that driver is still null because BasePage has not yet been instantiated. You will have to override the navigateTo method in some way to create a driver.
class BasePage extends PageObject {
@Managed
WebDriver driver;
public Alert waitingForAlert() throws InterruptedException {
Alert al = driver.switchTo().alert();
return al;
}
public void navigateTo() { // your code here ... }
}