简体   繁体   中英

null pointer exception in selenium java WebDriver

My code :

public class Testlogin {

    WebDriver driver;

    public Testlogin(WebDriver driver) {
        this.driver=driver;
    }

    WebElement userName = driver.findElement(By.id("username"));
    WebElement Password = driver.findElement(By.id("password"));
    WebElement login = driver.findElement(By.xpath("//button"));

    public void loginpages(String user,String pass) {
        userName.sendKeys(user);
        Password.sendKeys(pass);
        login.click();
    }
}

public class Testclass {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver(); 
        driver.get("https://the-internet.herokuapp.com/login");
        Testlogin test = new Testlogin(driver);
        test.loginpages("tomsmith","SuperSecretPassword!");
    }
}

Getting following error:

Exception in thread "main" java.lang.NullPointerException
    at Test.Testlogin.<init>(Testlogin.java:18)
    at Test.Testclass.main(Testclass.java:14)

the driver object has to be instatiated first. eg move it inside the constuctor:

public Testlogin(WebDriver driver)
{
    this.driver=driver;

    WebElement userName = driver.findElement(By.id("username"));
    WebElement Password = driver.findElement(By.id("password"));
    WebElement login = driver.findElement(By.xpath("//button"));

}

Make the testlogin class look like below if the driver is not yet set it will point to null and when you try to run driver.findElement(By.id("username")); and the driver is null this will not work to fix this do as Aiden Grossman said these will initialize when the driver is set

public class Testlogin {

    WebDriver driver;

    public Testlogin(WebDriver driver) {
        this.driver=driver;
        WebElement userName = driver.findElement(By.id("username"));
        WebElement Password = driver.findElement(By.id("password"));
        WebElement login = driver.findElement(By.xpath("//button"));
    }

    public void loginpages(String user,String pass) {
        userName.sendKeys(user);
        Password.sendKeys(pass);
        login.click();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM