Debasish
Debasish

Reputation: 1

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)

Upvotes: 0

Views: 350

Answers (2)

Matt
Matt

Reputation: 3187

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();
    }
}

Upvotes: 1

Gambotic
Gambotic

Reputation: 824

the driver object has to be instatiated first. e.g. 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"));

}

Upvotes: 1

Related Questions