首页 > 解决方案 > 需要帮助理解流畅的等待Java代码

问题描述

我正在尝试理解与 Selenium 中的 fluent Wait 相关的 Java 代码。代码如下:

WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
     public WebElement apply(WebDriver driver) {
       return driver.findElement(By.id("foo"));
     }
   });

我知道整个代码正在等待直到方法返回特定的 WebElement。但我的疑问与下面的代码片段有关。

new Function<WebDriver, WebElement>() {
         public WebElement apply(WebDriver driver) {
           return driver.findElement(By.id("foo"));
         }
       }

我也了解 Function 是一个内置的功能接口,它将 WebDriver 作为输入并返回 WebElement 作为输出。但是new关键字如何适合整个代码呢?

标签: seleniumfunctional-interfacefluentwait

解决方案


Fluent Wait 使用两个参数——超时值和轮询频率。

1.等待条件的最长时间

2.检查指定条件成功或失败的频率。

此外,如果您想将等待配置为忽略诸如 之类的异常,则可以将其添加到 Fluent Wait 命令语法中。

Wait wait = new FluentWait(driver)    
    .withTimeout(30, SECONDS)    
    .pollingEvery(5, SECONDS)   
    .ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function() {    
    public WebElement apply(WebDriver driver) {    
        return driver.findElement(By.id("foo"));    
    }
});

分析上面的示例代码。

1. Fluent Wait 以捕获开始时间来确定延迟开始。

2. Fluent Wait 然后检查 until() 方法中定义的条件。

3.如果条件失败,Fluent Wait 让应用程序按照pollingEvery(5, SECONDS)方法调用设置的值等待。在此示例中,为 5 秒。

4.在步骤 3 中定义的等待期满后,将根据当前时间检查开始时间。如果等待开始时间(步骤1中设置)与当前时间的差小于withTimeout(30, SECONDS)方法中设置的时间,则需要重复步骤2。

上述步骤将重复执行,直到超时到期或条件变为真。

函数是函数接口

@FunctionalInterface
public interface Function<T, R> {

/**
 * Applies this function to the given argument.
 *
 * @param t the function argument
 * @return the function result
 */
R apply(T t);

/**
 * Returns a composed function that first applies the {@code before}
 * function to its input, and then applies this function to the result.
 * If evaluation of either function throws an exception, it is relayed to
 * the caller of the composed function.
 *
 * @param <V> the type of input to the {@code before} function, and to the
 *           composed function
 * @param before the function to apply before this function is applied
 * @return a composed function that first applies the {@code before}
 * function and then applies this function
 * @throws NullPointerException if before is null
 *

推荐阅读