Macson Livera
Macson Livera

Reputation: 1

Getting Null pointer exception when declaring Webdriver as null outside the method and also declaring webdriver inside the method

Can some one explain why i am getting Null pointer exception when code execution reaches login() method in below script

public class TC_01_CreateEmployee {

WebDriver driver=null;

public void launchBrowser() throws Exception
{
    WebDriver driver=new ChromeDriver();
    driver.manage().window().maximize();
    Thread.sleep(2000);
}


public void login()
{
    driver.get("******");
    driver.findElement(By.id("txtUsername")).sendKeys("****");
    driver.findElement(By.id("txtPassword")).sendKeys("****");
    driver.findElement(By.id("btnLogin")).click();
}

Upvotes: 0

Views: 266

Answers (2)

Sureshmani Kalirajan
Sureshmani Kalirajan

Reputation: 1938

WebDriver driver=new ChromeDriver(); - This driver has a scope only within the method. The driver object which is used on the login method is still null. I am not sure why you would need 2 driver objects. you have 2 options to solve this,

public void launchBrowser() throws Exception
{
    WebDriver driver=new ChromeDriver();
    driver.manage().window().maximize();
    this.driver = driver;
    Thread.sleep(2000);
}

Or

public void launchBrowser() throws Exception
{
    driver=new ChromeDriver();
    driver.manage().window().maximize();
    Thread.sleep(2000);
}

Upvotes: 1

Greg Burghardt
Greg Burghardt

Reputation: 18783

It is likely that the launchBrowser() method is not being called before the login() method is being called.

An easy way around this is to define a getDriver() method that calls launchBrowser if driver is null.

private WebDriver getDriver() {
    if (driver == null) {
        launchBrowser();
    }

    return driver;
}

Then your login method looks like:

WebDriver driver = getDriver();

driver.get("******");
driver.findElement(By.id("txtUsername")).sendKeys("****");
driver.findElement(By.id("txtPassword")).sendKeys("****");
driver.findElement(By.id("btnLogin")).click();

Upvotes: 0

Related Questions