[英]Selenium (Java) - Keep clicking a button until specific text is present in an element and fail if certain amount of time is exceeded
I have a scenario where I can stop an engine by clicking a button which starts a background process and I can see the current status of the engine every time only after clicking a Refresh Status
button in the page.我有一个场景,我可以通过单击启动后台进程的按钮来停止引擎,并且每次只有在单击页面中的
Refresh Status
按钮后才能看到引擎的当前状态。 The issue is that the time varies for the engine to stop from 30 seconds to 2 mins depending upon the load on the server.问题是引擎停止的时间从 30 秒到 2 分钟不等,具体取决于服务器上的负载。 I really don't want to write a
while
loop with Thread.sleep()
as it's a bad idea and would unnecessarily increase the test time in selenium.我真的不想用
Thread.sleep()
编写一个while
循环,因为这是一个坏主意,并且会不必要地增加 selenium 的测试时间。 Is there an intuitive way to wait 20 seconds every time and click the Refresh Status
button until Offline
text is present in the element and have a timeout of 3 mins for this whole process?是否有一种直观的方法可以每次等待 20 秒并单击“
Refresh Status
按钮,直到元素中出现Offline
文本并且整个过程的超时时间为 3 分钟?
You can extend ExpectedConditions
class and override static method textToBePresentInElementLocated
if you would see the implementation is pretty much simple:如果您看到实现非常简单,您可以扩展
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);
}
};
}
Just add element.click() in this method to a proper place and then use your class extended class in WebDriverWait
只需将此方法中的 element.click() 添加到适当的位置,然后在
WebDriverWait
使用您的类扩展类
I would do something like this.我会做这样的事情。
/**
* 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;
}
You could also modify this code to be more flexible by passing polling interval and timeout as parameters.您还可以通过将轮询间隔和超时作为参数来修改此代码以使其更加灵活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.