How to resolve NullPointerException error in my below POM code?



  • I am getting java.lang.NullPointerException while executing my test case , I am using Page Object Modle with PageFactory ,following are the code snippets

    LoginPageObjec.java

    public class LoginPageObjects {
    
        @FindBy(xpath=".//*[@id='userName']")
        private WebElement email;
    
        @FindBy(xpath=".//*[@id='password']")
        private WebElement password;
    
        @FindBy(xpath=".//*[@id='loginFormSubmit']")
        private WebElement loginBtn;
    
        public void EnterUserName(String userName)
        {
            email.sendKeys(userName);
        }
    
        public void EnterPassword(String pass)
        {
            password.sendKeys(pass);
        }
    
        public void clickLogin()
        {
            loginBtn.click();
        }
    
    
    }
    

    LoginTC.java

    public class LoginTC extends BasePage{
        private WebDriver driver;
    
        @Test
        public void login()
        {
            LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);
            loginPage.EnterUserName("test.hr@domin.com.pk");
            loginPage.EnterPassword("test");
            loginPage.clickLogin();
        }
    public void login1()
            {
                LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);
                loginPage.EnterUserName("test.hr@domin.com.pk");
                loginPage.EnterPassword("test");
                loginPage.clickLogin();
            }
    
    }
    

    BasePage.java

    public class BasePage {
        private WebDriver driver;
    
        @BeforeMethod
          public void initializeBrowser() {
         driver=new FirefoxDriver();
         driver.navigate().to("https://nexthrm-dev.vteamslabs.com/");
         driver.manage().window().maximize();
         }
        @AfterMethod
        public void closeBrowser()
        {
            driver.close();
        }
    
    }
    

    I've extended BasePage class to utilize the (initialBrowser & closeBrowser) functions in my test case but its producing nullpointer exception if I copy both of the functions (initialBrowser & closeBrowser) into my LoginTC (testcase class) it works like charm but I dont want this redundant code i.e((initialBrowser & closeBrowser) for all my testcases class could anyone explain why I am getting nullpointer exception



  • The driver field in LoginTC hides the driver field from BasePage. The BasePage class fills in its own driver field, but LoginTC uses its own, which is never initialized.

    Solution: Remove the driver field from LoginTC, then either:

    • Make the driver field in BasePage public or protected.
    • Add a "getter" method (driver() or getDriver() or similar) to BasePage and use that to access the driver in derived classes.


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2