Search code examples
javaseleniumselenium-webdriverpage-factory

Getting java.lang.NullPointerException in POM uisng page Factory


I've posted below some sample code which I've done so far and I'm getting an Exception java.lang.NullPointerException.

Base Class:

public class TestBase {
    public static WebDriver driver= null;

    @BeforeSuite
    public void initialize(){
        System.setProperty("webdriver.chrome.driver","...chromedriver_win32\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("abcd.com");
    }

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

Login Page:

public class LoginPage {

    WebDriver driver;

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

    @FindBy(how=How.XPATH, using="//*[@id='email_id']") WebElement EmailTextBox;
    @FindBy(how=How.XPATH, using="//*[@id='password']")WebElement PassworTextBox;
    @FindBy(how=How.XPATH, using="//*[@id='frm_login']/div[4]/input") WebElement LoginButton;

    public void setemail(String strmail)
    {
        EmailTextBox.sendKeys(strmail);
    }

    public void setpwd(String strpwd)
    {
        try
        {
            PassworTextBox.sendKeys(strpwd);
        }
        catch (TimeoutException e) 
        {
            System.out.println("Time out exception " + e);
        } 
        catch (ElementNotSelectableException e) {
            System.out.println("Element not selectable exception " + e);
        } catch (NoSuchElementException e) {
            System.out.println("No such element found " + e);
        } catch (ElementNotVisibleException e) {
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Something Wrong " + e);
        }
    }

    public void ClickLoginBtn()
    {
        LoginButton.click();
    }
}

LoginTest class:

public class LoginTest extends TestBase{

    @Test
    public void init()
    {
        System.out.println("In the init method");
        LoginPage lg=PageFactory.initElements(driver, LoginPage.class);
        lg.setpwd("123123");
        lg.setemail("[email protected]");
        lg.ClickLoginBtn();
    }
}

I am getting the NullPointerException while setting the username and password. Could you please help me?

I am new to the POM with PageFactory so I dont have any idea How to resolve it but If anyone can help me with that it would be big help to me.


Solution

  • You shouldn't initialise the WebDriver instance i.e. driver twice as follows:

    public static WebDriver driver= null;
    

    and

    WebDriver driver=new ChromeDriver();
    

    Keep the global declaration as:

    public static WebDriver driver= null;
    

    And channge the line as:

    driver=new ChromeDriver();