user4528549
user4528549

Reputation:

Getting java.lang.NullPointerException when trying to use @FindBy in webDriver

I am getting java.lang.NullPointerException when i am trying to find elements on a webpage using @FindBy annotation.

My Code -

public class pageObject{
  WebDriver driver;

  @FindBy(id = "email")
  WebElement searchBox;
  @FindBy(id = "u_0_v")
  WebElement submit;

  void pageObject(String web){
    FirefoxProfile profile = new FirefoxProfile();
    profile.setAssumeUntrustedCertificateIssuer(false);
    profile.setAcceptUntrustedCertificates(false);
    this.driver = new FirefoxDriver(profile);
    this.driver.get(web);
    this.driver.manage().window().maximize();
    this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    searchBox.click();
    searchBox.sendKeys("er");
    submit.click();
  }

  public static void main(String[] args){
    new pageObject("https://www.facebook.com/?_rdr=p");
  }
}

I got an exception for the above code -

Exception -

Exception in thread "main" java.lang.NullPointerException
at com.Selenium_Practice.pageObject.<init>(pageObject.java:29)
at com.Selenium_Practice.pageObject.main(pageObject.java:35)

I also tried to use

 @FindBy(how = HOW.ID , using = "email")  and @FindBy(how = HOW.ID , using = "u_0_v")

but again got the same null pointer exception

Upvotes: 1

Views: 4015

Answers (1)

drkthng
drkthng

Reputation: 6929

You first need to init your Elements if you use Selenium's PageFactory and if you want your class to be self-containing*

pageObject(String web){

    FirefoxProfile profile = new FirefoxProfile();
    profile.setAssumeUntrustedCertificateIssuer(false);
    profile.setAcceptUntrustedCertificates(false);
    this.driver = new FirefoxDriver(profile);

    // You need to put this line in your constructor
    PageFactory.initElements(this.driver, this);

    // Then follows the rest of your constructor
    ...
}

* meaning, that you could also init this classes elements outside the class, but I presume you want to do it inside.

Upvotes: 1

Related Questions