【问题标题】:Getting java.lang.NullPointerException when trying to use @FindBy in webDriver尝试在 webDriver 中使用 @FindBy 时出现 java.lang.NullPointerException
【发布时间】:2015-09-03 12:00:38
【问题描述】:

当我尝试使用 @FindBy 注释在网页上查找元素时,出现 java.lang.NullPointerException。

我的代码 -

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");
  }
}

上面的代码有一个异常-

例外-

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)

我也试过用

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

但又得到了同样的空指针异常

【问题讨论】:

    标签: java selenium nullpointerexception testng pageobjects


    【解决方案1】:

    如果你使用 Selenium 的 PageFactory 并且你希望你的类是自包含的,你首先需要初始化你的元素*

    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
        ...
    }
    

    * 意思是,你也可以在类之外初始化这个类元素,但我想你想在里面做。

    【讨论】:

    • 先生,我把 PageFactory.initElements(driver, this);在我的构造函数中作为第一行但我再次在 org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69) 的 org.openqa.selenium 的线程“main”java.lang.NullPointerException 中得到 NullPointerException 异常.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38) at com.sun.proxy.$Proxy2.click(Unknown Source) at com.Selenium_Practice.pageObject.(pageObject.java:31) at com.Selenium_Practice.pageObject.main(pageObject.java:37)
    • 抱歉错字!当然,这一行需要在您实例化驱动程序变量之后出现! -> 查看我的更新
    • 它现在可以工作了。先生如何在类之外初始化这个类元素?
    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    相关资源
    最近更新 更多