Selenium - PageObjectFactory - 重新加载后在同一页面上引用元素

时间:2014-10-20 03:40:30

标签: java selenium-webdriver webdriver

我正在使用Webdriver和Java测试网页。

测试页面包含记录列表,我点击"员工ID"标题超链接和记录应按员工ID的升序排序,并且"员工ID旁边应该有一个小图标"列表示结果现在已排序。

这是我的代码:

public Class ResultsPage extends SlowLoadableComponent<ResultsPage> {

    @FindAll({ @FindBy(how = How.XPATH, using = "some xpath"), @FindBy(how = How.XPATH, using = "another xpath") })
    public List<WebElement> resultsTableElement;

    @FindBy(how = How.XPATH, using = "//a[@title='A system assigned identifier for the Employee record.']")
    public WebElement employeeIDColumnTitle;

    @FindBy(how = How.XPATH, using = "//a[@title='A system assigned identifier for the Employee record.']/following-sibling::img")
    public WebElement ascOrDescIcon;

    public ResultsPage(WebDriver driver) {
        super(new SystemClock(),20);
        this.driver = driver;
        wait = new WebDriverWait(driver, Start.TIME_OUT);
        PageFactory.initElements(driver,this);
    }

    @Override
    protected void load() {
        PageFactory.initElements(driver, this);
        LOGGER.info("From the load method");
    }

    @Override
    protected void isLoaded() throws Error {
        boolean loaded = false;
        if (resultsTableElement.size() > 0) {
            loaded = true;
        }
        LOGGER.warn("isloaded method failed ");
        Assert.assertTrue(loaded, "Looks like the Claim Results Search Frame is not loaded yet");
    }

    public void testThis() {
        //some code here
        systemIDColumnTitle.click();
        PageFactory.initElements(driver, this); //Calling the initElements of the same page again to see that the element 
        LOGGER.info(ascOrDescIcon.getAttribute("src")); //This line always fails saying that the element is not found.
    }

}

1 个答案:

答案 0 :(得分:1)

根据您指定的评论,为什么您不能在同一页面对象中定义定位器,如:

@FindBy(id="newElement")
private WebElement newElement

newElement指向在某些操作后创建的新元素。

编辑:

根据您的评论,您可以直接调用get方法而不是实例化另一个时间。请理解,所有@FindBy WebElements都是代理人;只有在您调用方法时,才会获取它们(使用您给定的定位器)并执行特定操作。

这就是原因,您可以在页面对象上添加元素并调用initElements不会抛出错误,即使@FindBy找不到!