1

出于某种原因,当我调用方法 Spage.editExButton(int ID) 时,我收到一条错误消息,指出 WebElement first 为空。为什么它是空的?我已经使用 @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);
}
4

4 回答 4

9

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

PageFactory.initElements(getDriver(), this);

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

于 2013-07-23T18:49:44.730 回答
1

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

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

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);
}
于 2018-12-25T10:51:28.153 回答
0

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

WebMainMenu mainmenu = PageFactory.initElements(驱动程序,WebMainMenu.class);

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

ETC

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

于 2014-10-06T21:57:49.017 回答
0
WebElement first;

是 null 因为当我们实例化我们的页面类时元素没有被初始化。所以初始化页面类中的所有元素

 PageFactory.initElements(driver,  this); 
于 2018-12-24T14:52:47.283 回答