2

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
2
  • can u please paste web element tag on which u want to click Commented Apr 3, 2019 at 11:17
  • @Ravi Yes, so the tag is: ``` <i class="ico fa fa-lock"></i> ``` URL: phptravels.com/demo Commented Apr 3, 2019 at 12:03

5 Answers 5

3

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()");
Sign up to request clarification or add additional context in comments.

4 Comments

Nope, still no luck!
can u try this className = "login"
@PeterR Can you try with javascript click , the last line in edited answer by replacing your loginButton.click() with this
@PeterR Try javascript click
1

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

5 Comments

can you please elaborate on you answer, particularyl when you said "Nullpointer is because loginButton is null, probably because it is not initialized."?
the annotation @FindBy, is going to find the login button. however, when you execute and the classes that you are looking for are not found on the page, the loginButton object is not being initialized.
And when you call a method on the null object, you get a Null Pointer Exception
You may upvote the answer, if I was able to help :-)
+1 for quick response to query, but when we use @FindBy(className="something") we don't need to use '.' as prefix
1

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)

9 Comments

Thank you for your quick reply to my query. This realtes to this URL: phptravels.com/demo Which when you use the dev tools to check this button, this is the name of the class "ico fa fa-lock".
@PeterR As I wrote in my answer it's not one class, those are 3 classes: ico, fa and fa-lock.
@PeterR Add to your question the stackrace and the driver and PageFactory initialization.
something like this? <b/> public HomePage (WebDriver driver){ super(driver); PageFactory.initElements(driver, this); //page instantiation } public void logInBut(){ loginButton.click(); }
@PeterR Yes. Did you try?
|
1

Try the follwoing code.

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

Or

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

2 Comments

@PeterR : I am able to click on the login button the link you have shared to OP.Strange.
Really? Can you share your code snippet here, showing it working, please?
1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.