我有一个场景,我可以通过单击启动后台进程的按钮来停止引擎,每次只有在单击页面中的Refresh Status
按钮后才能看到引擎的当前状态。问题是发动机停机时间从30秒到2分钟不等,具体取决于服务器上的负载。我真的不想用while
写一个Thread.sleep()
循环,因为这是一个坏主意,会不必要地增加硒的测试时间。是否有直观的方法每次等待20秒并单击Refresh Status
按钮,直到元素中出现Offline
文本,并且整个过程的超时时间为3分钟?
答案 0 :(得分:1)
如果你看到实现非常简单,你可以扩展ExpectedConditions
类并覆盖静态方法textToBePresentInElementLocated
:
public static ExpectedCondition<Boolean> textToBePresentInElementLocated(
final By locator, final String text) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
String elementText = findElement(locator, driver).getText();
return elementText.contains(text);
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return String.format("text ('%s') to be present in element found by %s",
text, locator);
}
};
}
只需将此方法中的element.click()添加到适当的位置,然后在WebDriverWait
答案 1 :(得分:0)
我会做这样的事情。
/**
* Attempts to stop the engine within a specified time
*
* @param driver
* the WebDriver instance
* @return true if the engine has stopped, false otherwise
* @throws InterruptedException
*/
public boolean StopEngine(WebDriver driver) throws InterruptedException
{
driver.findElement(By.id("stopEngineButton")).click(); // click the stop engine button
boolean found = false;
int i = 0;
while (!found && i < 6) // 6 * 20s = 2 mins
{
Thread.sleep(20000);
driver.findElement(By.id("RefreshStatus")).click(); // click the Refresh Status button
// not sure if you need a wait here to let the statusElement update
found = driver.findElement(By.id("statusElement")).getText().equals("Offline"); // compare the current engine status to Offline
i++;
}
return found;
}
您还可以通过将轮询间隔和超时作为参数传递来修改此代码以使其更加灵活。