【问题标题】:Need help understanding the fluent wait Java code需要帮助理解流畅的等待Java代码
【发布时间】:2020-07-07 11:47:35
【问题描述】:

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

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

我知道整个代码正在等待由 until 方法返回的特定 WebElement。但我的疑问与以下代码有关。

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

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

【问题讨论】:

    标签: selenium functional-interface fluentwait


    【解决方案1】:

    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。

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

    Function是函数接口

    @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
     *
    

    【讨论】:

    • 对不起,答案是我已经知道的,而不是我正在寻找的。我试图了解代码中的 Function 部分与 Java 相关的内容。
    • 不寻找已经存在的 Java 文档
    猜你喜欢
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多