首页 > 解决方案 > 将 isExists 函数添加到 WebElement

问题描述

我想扩展 selenium 并实现这样的东西:

public class IsExistsWebElement extends WebElement {

    public boolean isExists() {
        try {
            this.getText();
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

}

然后像这样使用它(使用页面工厂):

public class HomePage{

    @FindBy(class = "button")
    private IsExistsWebElement button;

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

    public boolean isButtonExists() {
        return this.button.isExists();
    }
} 

实现这样的事情的最佳方法是什么?

标签: javaselenium

解决方案


如果您正在寻找自定义实现,那么您必须在 selenium 之上创建一个新框架,并且必须为大多数事情编写自己的实现。

例如RemoteWebElement类实现了WebElement接口。但是仅仅在代码下面编写并像我们为 WebElement 所做的那样具有访问权限并不简单

例如IsExistsWebElement element = driver.findElement(By.id("a"));

class IsExistsWebElement extends RemoteWebElement {
    public boolean isExists() {
        try {
            this.getText();
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }
}

如果您正在寻找基于 selenium 的新框架并且能够负担得起时间(可能是 3、6、9 .. 个月,取决于资源)和成本,那么请愉快地去争取。

或者

然后在页面对象模型中寻找以通用方式管理等待

  1. 创建一个 BasePage 类
  2. 在构造函数中启动显式等待
  3. 为存在、可见性等创建等待方法
  4. 在您的其他页面类中扩展此 BasePage 类

例如

public BasePage(WebDriver driver) {
    this.driver = driver;
    wait = new WebDriverWait(driver, TIMEOUT, POLLING);
    PageFactory.initElements(new AjaxElementLocatorFactory(driver, TIMEOUT), this);
}


public void waitForElementReady(WebElement element) {
    try {
        wait.until(ExpectedConditions.visibilityOf(element));
    } catch (TimeoutException exception) {
        System.out.println("Element didn't find in given time");
    }
}

推荐阅读