使用Selenium2 ExpectedCondition的Lambda表达式用法?

时间:2013-08-31 21:08:37

标签: lambda webdriver selenium-webdriver

在阅读了有关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") );
       }
  } );

3 个答案:

答案 0 :(得分:2)

基本上,虽然lamdas are not just anonymous classes - 当你想讨论动词并在过去必须使用匿名类的地方提供更简洁的代码时,它们真的有用。

我们想告诉Selinium等到行动发生。使用旧语法,我们必须创建一个新的ExpectedCondition接口的匿名实现 - 使用lambdas不再是这种情况。

因此,假设Selinium将支持此语法,它应该类似于:

wait.until(webDriver -> webDriver.findElement(By.id("foo")))

减少代码的长度,使其更具可读性。

更一般地说:

new Interface{
    public ReturnValue action(Type first,Type second...){
         return SomeExpression();
    }
}

变为:

(first,second) -> SomeExpression();

答案 1 :(得分:1)

从Selenium版本3.2.0开始,until()方法将仅接受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")));

答案 2 :(得分:0)

不完全。使用Java 8,我们应该能够替换实现&#34;单个抽象方法接口的匿名内部类&#34; 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只接受ONE&#34;单个抽象方法接口&#34;时才有效。因为在接受多个之前,您将收到以下编译时错误:

直到(谓词)方法对于类型是不明确的  FluentWait