【问题标题】:Webelement defined by @FindBy annotation returns null pointer@FindBy 注解定义的 Web 元素返回空指针
【发布时间】:2018-12-25 18:51:28
【问题描述】:

由于某种原因,当我调用方法 Spage.editExButton(int ID) 时,我收到一条错误消息,指出 WebElement first 为 null。为什么它是空的?我已经使用 @FindBy 注释定义了它。我必须使用 findElement(By.id("xxx")) 显式定义元素才能单击它。但是为什么我不能使用 @FindBy 表示法来调用它?

public class SPage extends GPage<SPage> {

    public SPage() {
        super();
    }

    public SPage(String pageType) {
        super(pageType);
    }

    @FindBy(id = "xxx")
    WebElement first;

    public WebElement eButton(int ID) {
        first.click();
        String tmp = ID + "-Edit";
        WebElement edit = getDriver().findElement(By.id(tmp));
        return edit;
    }

    public EPage cEdit(int ID) {
        eButton(ID).click();
        return new EPage(getBasePageType()).openPage(EPage.class);
    }
}

我这样调用方法:

static EPage epage;
static SPage spage;

@Test
public void edit_exception() {
             epage = spage.cEdit(IDbefore);
}

【问题讨论】:

  • 从给出的代码看来,你还没有初始化WebElement first,所以默认情况下它的nullNPE抛出first.click();
  • 你是如何创建SPage 的这个实例的?它是 Selenium 给你的吗?
  • 我添加了更多关于如何调用我的方法的信息。

标签: java selenium nullpointerexception webdriver selenium-webdriver


【解决方案1】:

你需要调用它(最好在你的构造函数中):

PageFactory.initElements(getDriver(), this);

更多信息:https://code.google.com/p/selenium/wiki/PageFactory

【讨论】:

【解决方案2】:

正如所有其他答案提到的,我们必须使用 PageFactory.initElements() 初始化 webElements,

有两种方法可以做到,或者更确切地说是两个地方可以做到:

1) 在 SPage 类中

由于 SPage 类中有两个构造函数,我们必须添加以下代码来初始化该类中声明的所有元素,这应该在两个类中完成,因为我们不知道哪个构造函数将用于初始化SPage

我们会将驱动程序实例传递给 SPage 类构造函数,如下所示:

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

public SPage(String pageType, WebDriver driver) {
    super(pageType);
    PageFactory.initElements(driver, this);
}

2) 在要使用 SPage WebElements 的其他类中 :

在上面的示例中,元素可以在编写edit_exception()方法的类中初始化,总之在我们要使用类SPage的元素/动作的任何地方之前, 现在代码如下所示:

@Test
public void edit_exception() {
             spage =  PageFactory.initElements(driver, SPage.class);  //we are not passing driver instance to SPage class
             epage = spage.cEdit(IDbefore);
}

【讨论】:

    【解决方案3】:

    在我的测试类中,我添加了以下代码行

    WebMainMenu mainmenu = PageFactory.initElements(driver, WebMainMenu.class);

    mainmenu.doStuff(驱动程序, 5);

    我同意如上所述,您需要实例化页面对象。

    【讨论】:

      【解决方案4】:
      WebElement first;
      

      为空,因为在我们实例化页面类时元素没有被初始化。所以初始化页面类中的所有元素

       PageFactory.initElements(driver,  this); 
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 2022-01-12
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多