Null Pointer Exception Being returned - Java Selenium Webdriver

人盡茶涼 提交于 2020-03-23 07:30:19

问题


Getting Null Pointer exception when running test in Selenium WebDriver with Java. For some reason the test is retunrning null, even everything is being declared correctly (I think?).

What am I missing/doing wrong here?

//Given this code:

public class HomePage extends DriverSetup{

    @FindBy(className = "ico fa fa-lock")
    static WebElement loginButton;

    public HomePage (WebDriver driver){
        super(driver);
    }


  public static void logInBut(){
        loginButton.click();
  }```



//When running this test:


```public class test1 extends DriverSetup{

    public test1() {
        super(driver);
    }

    @Test
    public void signIn(){

        getDriver().get(URL);

        HomePage.logInBut();

        logInPage.inEmail(" ");
        logInPage.inPassword(" ");


    }```


//Driver Set up:

```public class DriverSetup {

    public static WebDriver driver;

    public DriverSetup(WebDriver driver) {
    }

    public WebDriver getDriver() {
        if(this.driver == null) {
            this.setUp();
        }
        return this.driver;
    }

    public void FindByInitialization (WebDriver driver){
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    //Set up Driver
    @BeforeClass //Before executing any test in the class do this
    public static void setUp(){

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Peter.Redondeiro\\Documents" +
        "\\IDEA projects\\ChromeDriver\\chromedriver_win32\\chromedriver.EXE");

        driver = new ChromeDriver();
        driver.manage().window().maximize(); //maximise window when open
    }

    //clear all the cookies after executing each test
    @After
    public void clearCookies(){
        driver.manage().deleteAllCookies(); //delete all the cookies
    }

    //Close browser after executing all the tests in the class
    @AfterClass
    public static void closeBrowser(){
        driver.close();
    }

}```


//Log in page object:

public class logInPage extends DriverSetup{

    //Find the input email box in Login page
    @FindBy(id = "inputEmail")
    private static WebElement inputEmail;

    //Find input password box in Login page
    @FindBy(id = "inputPassword")
    private static WebElement inputPassword;

    //Find LogIn button in Login page
    @FindBy(id = "login")
    private static WebElement logInButton;

    public logInPage(WebDriver driver) {
        super(driver);
    }

    //Confirm that you are on the Login page
    public static String confirmationHeader(){
        return header.getText();
    }

    //Method to enter email in email box
    public static void inEmail(String inEmail){
       inputEmail.sendKeys(inEmail + emailGenerator.randomEmailGenerator());
    }

    //Method to enter password in password box
    public static void inPassword(String PassInput){
       inputPassword.sendKeys(PassInput + passwordGenerator.randomPasswordGenerator());
    }
}```

This is the stack trace of the above code execution:

java.lang.NullPointerException
    at logInPage.inEmail(logInPage.java:46)
    at test1.signIn(test1.java:15)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)


Process finished with exit code -1

回答1:


U are getting NPE(Null pointer exception) on line

loginButton.click();

it means you are doing some operation on object which got a null value and in this case it is none other than your loginButton

now the question comes up, Why login button is null when you are initialising it with

@FindBy(className = "ico fa fa-lock")
static WebElement loginButton;

it is possible because of web driver is not able to find this element and hence it is null

try following suggestions

public HomePage(WebDriver driver) {
    super(driver);
    PageFactory.initElements(driver, this);
}

and if this does not work try with single class name like this

@FindBy(className = "ico")
private WebElement loginButton;

@FindBy(className = "login")
List<WebElement> buttons;

and while clicking like this

buttons.get(0).click();

else try with javascript click direct, it should surely work

((JavascriptExecutor)driver).executeScript("document.getElementsByClassName('login')[0].click()");



回答2:


Please check line number 55 in HomePage.java

It says

loginButton.click();

Nullpointer is because loginButton is null, probably because it is not initialized.

Most probably because it is not able to find the element by the classes that you have mentioned.

You might want to use '.' in front of the class names




回答3:


loginButton is null because the locator you specified didn't match anything. className takes one class as parameter, you used three. To use more than one class you need to use cssSelector

@FindBy(css = ".ico.fa.fa-lock")
static WebElement loginButton;

Or xpath

@FindBy(xpath = "//*[@class='ico fa fa-lock']")
static WebElement loginButton;

Don't forget to initialize it PageFactory.initElements(driver, HomePage)




回答4:


Try the follwoing code.

@FindBy(className = "login")
static WebElement loginButton;

Or

@FindBy(xpath ="//a[@class='login']")
static WebElement loginButton;



回答5:


Credits to @Ravi, the Answer to my query is the below:

public class HomePage extends DriverSetup{

    @FindBy(className = "login")
    private static List<WebElement> buttons;

    public HomePage (WebDriver driver){
        super(driver);
    }

  public static void logInBut(){
      ((JavascriptExecutor)driver).executeScript("document.getElementsByClassName('login')[0].click()");
  }
}
//Trying with javascript click because of environment issue driver was not able to find elements with @FindBy, hence the web element was null and it was throwing NullPointerException

//If you need to read through to understand please see the comments and read @Ravi's comments in particular!


来源:https://stackoverflow.com/questions/55493161/null-pointer-exception-being-returned-java-selenium-webdriver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!