问题描述
org.openqa.selenium.support.ui.FluentWait
的until()
方法是否重载了Predicate<T>
和Function<? super T, V>
Function<? super T, V>
接口作为参数。
它应该作为以下之一的参数(实现apply()
方法):
- 匿名课
- Lambda表达
- 方法参考
我定义为此方法的参数的任何lambda都会抛出以下错误:
直到(Predicate)方法对于WebDriverWait类型是不明确的
我的Lambda:
x -> x.findElement(byLocator).isDisplayed()
我假设任何lambda都是这种情况,因为函数或Predicate的apply()
可以通过使用这些lambda来实现。
所以我的问题是什么是使用Predicate作为参数的until方法?
更新:删除了@drkthng回答的问题的第一部分。
1楼
回答你的第一个问题:
查看的 。
我引用:
public interface ExpectedCondition<T>
extends com.google.common.base.Function<WebDriver,T>
你看,ExpectedCondition继承自google的Function接口,因此你可以将它用作until()方法的参数。
至于你的第二个问题:
我认为你不能像那样交出一个lambda。 直到方法等待谓词或函数(正如您正确提到的那样)。
关于Predicates和lambdas之间的区别,请在查看示例
所以你可以尝试这样的东西,仍然使用你的lambda表达式:
Predicate<WebDriver> myPredicate = x ->x.findElement(By.id("id")).isDisplayed();
WebDriverWait wait = (WebDriverWait)new WebDriverWait(driver, 10);
wait.until(myPredicate);
2楼
如你所说的方法until
过载和预期的参数是Predicate<T>
和Function<? super T, V>
Function<? super T, V>
。
你的lambda表达式匹配两个签名,因此对方法的调用是不明确的,为了解决歧义,有几个选项:
将lambda表达式转换为所需的类型:
until((Predicate<WebDriver>) x -> x.findElement(byLocator).isDisplayed());
如果为lambda表达式创建变量,则不需要强制转换:
Predicate<WebDriver> p = x.findElement(byLocator).isDisplayed();
until(p);
如果您有一个具有此功能的方法,则可以使用方法引用:
boolean testMethod(WebDriver x) {
return x.findElement(byLocator).isDisplayed();
}
until(MyClass::testMethod);
3楼
当lambda表达式与谓词和函数匹配时,您将收到错误。
考虑将selenium升级到v3.2.0 - >,其中不推荐使用FluentWait.until(Predicate<?>)
方法。
这应该使lambdas现在可以正常使用Wait实例。
4楼
下面的功能接口实现应解决问题:
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
wait.pollingEvery(500, TimeUnit.MILLISECONDS);
wait.withTimeout(5, TimeUnit.MINUTES);
wait.ignoring(NoSuchElementException.class);
wait.until((WebDriver arg0) ->{
WebElement element = arg0.findElement(By.id("colorVar"));
String color = element.getAttribute("style");
System.out.println("The color if the button is " + color);
if(color.equals("color: red;"))
{
return true;
}
return false;
});