问题描述
使用HTML"Selenium 测试(使用 Selenium IDE 创建或手动创建),您可以使用一些 非常方便的命令,例如 WaitForElementPresent
或 WaitForVisible
.
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(),它将条件设置为一个确切的时间段等待.提供了一些方便的方法来帮助您编写只等待所需时间的代码.WebDriverWait in与 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 的等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!