最近在学习自动化测试,之前同事写的代码充斥着大量的Thread.sleep(),今天对相关代码进行了替换,在此总结下WebDriver的显示等待的一些经验。
WebDriver的显示等待大概脉络如下:
通过研读源码可以知道,WebDriverWait是FluentWait的子类(设置poll的sleeptime为500ms且忽略NotFoundException)
,在使用中,通常给它们的实例的until方法传入ExpectedConditions的静态方法或者一个Function的实例来调用,常见代码如下:
此处以FluentWait类作为示范:
1. 配合ExpectedConditions类的静态方法
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(300,TimeUnit.SECONDS)
.pollingEvery(50,TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class)
.ignoring(InvalidSelectorException.class);
List<WebElement> webElements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(exceptStrTemp)));
if (webElements != null && webElements.size() > 0)
{
status = true;
}
2. 搭配New Function,在使用中发现如果返回对象为List<WebElement>时,apply方法只会被执行一次,导致失效。
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(300,TimeUnit.SECONDS)
.pollingEvery(50,TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class);
//只能尝试定位一个对象,不可定位List,否则不生效
WebElement webElement = wait.until(new Function<WebDriver,WebElement>() {
@Nullable
@Override
public WebElement apply(@Nullable WebDriver webDriver) {
log.debug("WebDriverWait的 apply方法被调用!");
return driver.findElement(By.xpath(exceptStrTemp));
}
});