在使用 Java 的 Selenium WebDriver 测试中等效于 waitForVisible/waitForElementPresent? [英] Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

查看:30
本文介绍了在使用 Java 的 Selenium WebDriver 测试中等效于 waitForVisible/waitForElementPresent?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用HTML"Selenium 测试(使用 Selenium IDE 创建或手动创建),您可以使用一些 非常方便的命令,例如 WaitForElementPresentWaitForVisible.

With "HTML" Selenium tests (created with Selenium IDE or manually), you can use some very handy commands like WaitForElementPresent or WaitForVisible.

<tr>
    <td>waitForElementPresent</td>
    <td>id=saveButton</td>
    <td></td>
</tr>

在用 Java 编写 Selenium 测试时(Webdriver/Selenium RC——我不确定这里的术语),是否有类似的内置功能?

When coding Selenium tests in Java (Webdriver / Selenium RC—I'm not sure of the terminology here), is there something similar built-in?

例如,用于检查对话框(需要一段时间才能打开)是否可见...

For example, for checking that a dialog (that takes a while to open) is visible...

WebElement dialog = driver.findElement(By.id("reportDialog"));
assertTrue(dialog.isDisplayed());  // often fails as it isn't visible *yet*

编写此类检查的最简洁稳健方法是什么?

What's the cleanest robust way to code such check?

在所有地方添加 Thread.sleep() 调用将是丑陋和脆弱的,并且滚动你自己的 while 循环似乎也很笨拙......

Adding Thread.sleep() calls all over the place would be ugly and fragile, and rolling your own while loops seems pretty clumsy too...

推荐答案

隐式和显式等待

隐式等待

Implicit and Explicit Waits

Implicit Wait

隐式等待是告诉 WebDriver 轮询某个特定的 DOM尝试查找一个或多个元素(如果它们是)的时间不是立即可用.默认设置为 0.一旦设置,为 WebDriver 对象实例的生命周期设置隐式等待.

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

显式等待 + 预期条件

显式等待是您定义的等待特定条件的代码在代码中进一步处理之前发生.最坏的情况是 Thread.sleep(),它将条件设置为一个精确的时间段等待.提供了一些方便的方法来帮助您编写仅在需要时等待的代码.WebDriver 等待与 ExpectedCondition 相结合是一种方法完成.

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

这篇关于在使用 Java 的 Selenium WebDriver 测试中等效于 waitForVisible/waitForElementPresent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆