在阅读了一篇关于JDK1.8和Lambda表达式的文章之后,我意识到我过去几年一直使用的ExpectedCondition块可能适合作为Lambda表达式来表示。
给定这个等待对象:
Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring( NoSuchElementException.class );有人能告诉我如何将Selenium的ExpectedCondition表达式转换为Lambda表达式吗?
WebElement foo = wait.until( new ExpectedCondition<Boolean>() {
public WebElement apply( WebDriver webDriver ) {
return webDriver.findElement( By.id("foo") );
}
} );发布于 2017-08-31 13:17:13
在Selenium3.2.0版本中,直到()方法将只接受Function<T,K>作为参数,并且接受Predicate<T> 作为参数是不推荐的。
上面的决定是使用lambda表达式。
因此,要回答你的问题:
Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
//lamda expression:
WebElement foo = wait.until(d -> d.findElement(By.id("foo")));发布于 2013-08-31 21:53:00
基本上,虽然lamdas are not just anonymous classes --当您想要讨论动词和提供更简洁的代码时,它们确实有帮助--但是过去必须使用匿名类。
我们想要告诉Selinium,等着行动发生。使用旧的语法,我们必须为ExpectedCondition接口创建一个新的匿名实现--而lambda则不再是这种情况了。
因此,假设Selinium将支持这种语法,它应该如下所示:
wait.until(webDriver -> webDriver.findElement(By.id("foo")))减少代码的长度,并使其更具可读性。
更广泛地说:
new Interface{
public ReturnValue action(Type first,Type second...){
return SomeExpression();
}
}变成:
(first,second) -> SomeExpression();发布于 2017-03-18 00:00:21
不完全是。使用Java 8,我们应该能够用lambda替换实现“单个抽象方法接口”的匿名内部类,如下所示:
new FluentWait<WebDriver>( driver ) // Would be nice!
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring( NoSuchElementException.class )
.until(wd -> wd.findElements(By.id("foo")).size() == 1);问题是,只有当接收方法FluentWait.until只接受一个“单个抽象方法接口”时,这才有效。因为在接受多个之前,您将得到以下编译时错误:
对于类型FluentWait,直到(谓词)是不明确的方法
https://stackoverflow.com/questions/18552851
复制相似问题