代码之家  ›  专栏  ›  技术社区  ›  user4528549

尝试在webDriver中使用@FindBy时获取java.lang.NullPointerException

  •  1
  • user4528549  · 技术社区  · 11 年前

    当我试图使用@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")
    

    但再次出现相同的空指针异常

    1 回复  |  直到 11 年前
        1
  •  1
  •   drkthng Mesut GUNES    11 年前

    如果您使用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
        ...
    }
    

    *这意味着,您也可以在类外部初始化这些类元素,但我想您应该在内部初始化。