AndroidElement 和 WebDriver 等待方法问题

AndroidElement and WebDriver wait method issue

我希望能够在我的移动自动化套件中多次使用相同的方法。意味着每次我只是调用方法并只更新 "elementName" (AndroidElement).

我试过了:

 public void waitForScreenToLoad(AndroidElement elementName){
        (new WebDriverWait(driver,30)).until(ExpectedConditions.presenceOfElementLocated(By.id(elementName.getId())));
    }

在我的测试中我会这样称呼它

MessageCenterScreen message = new MessageCenterScreen(driver);

base.waitForScreenToLoad(message.addCardButton);

但是我的测试失败了,因为它找不到一个存在的元素。

我使用 Page Factory 模型来定位元素

   @FindBy(id = "widget_loading_fab_button")
        public AndroidElement addCardButton;

这种方式效果很好,但问题是:我不想一直重复我的方法。

public void waitForCardManagementScreenToLoad() {
        (new WebDriverWait(driver, 30)).until(ExpectedConditions.presenceOfElementLocated(By.id("widget_loading_fab_button")));
    } 
  public void waitForScreenToLoad(AndroidElement element){
        (new WebDriverWait(driver,30)).until(ExpectedConditions.visibilityOf(element));
    }

使用ExpectedConditions.visibilityOf

我会粘贴我在之前的 post

中帮助过某人的内容

我创建了一个带有默认时间的时间参数的基本 waitUntil 方法。

    private void waitUntil(ExpectedCondition<WebElement> condition, Integer timeout) {
    timeout = timeout != null ? timeout : 5;
    WebDriverWait wait = new WebDriverWait(driver, timeout);
    wait.until(condition);
}

然后我可以使用该辅助方法来创建等待显示或等待可点击。

    public Boolean waitForIsDisplayed(By locator, Integer... timeout) {
    try {
        waitUntil(ExpectedConditions.visibilityOfElementLocated(locator),
                (timeout.length > 0 ? timeout[0] : null));
    } catch (org.openqa.selenium.TimeoutException exception) {
        return false;
    }
    return true;
}

您可以对 elementToBeClickable 执行类似的操作。

    public Boolean waitForIsClickable(By locator, Integer... timeout) {
    try {
        waitUntil(ExpectedConditions.elementToBeClickable(locator),
                (timeout.length > 0 ? timeout[0] : null));
    } catch (org.openqa.selenium.TimeoutException exception) {
        return false;
    }
    return true;
}

所以我们可以做一个点击方法来做我们的点击使用这个:

    public void click(By locator) {
    waitForIsClickable(locator);
    driver.findElement(locator).click();               
}

我制作 waitForIsDisplayed 和 waitForIsClickable 的原因是因为我可以在我的断言中重用它们以减少它们的脆弱性。

assertTrue("Expected something to be found, but that something did not appear",
            waitForIsDisplayed(locator));

此外,您可以使用方法中指定的默认时间(5 秒)的等待方法,或者可以这样做:

waitForIsDisplayed(locator, 20);

在抛出异常之前最多等待 20 秒。