在 FluentWait 用法中使用 lambda 函数和不使用它有什么区别?

What is the difference between using lambda function in FluentWait usage and not using it?

等待一个元素可以编码为

WebElement foo = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("foo")));

在FluentWait的文档中,下面给出了一个示例,排除了超时、轮询间隔、异常忽略的定义。

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

两者有什么区别?有什么额外的好处吗?

我搜索了 lambda 表达式、函数式接口。但是我没看懂。

WebDriverWait

WebDriverWait 是使用 WebDriver 实例的 FluentWait 的特化。

构造函数是:

  • WebDriverWait(WebDriver driver, java.time.Clock clock, Sleeper sleeper, long timeOutInSeconds, long sleepTimeOut)
  • WebDriverWait(WebDriver driver, long timeOutInSeconds):诱导此Wait将忽略在'until'条件下默认遇到(抛出)的NotFoundException实例,并立即传播所有其他人。
  • WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis):诱导此Wait将忽略在'until'条件下默认遇到(抛出)的NotFoundException实例,并立即传播所有其他人。

WebDriverWait 的 Lambda 实现

示例 A:

(new WebDriverWait(driver(), 5))
    .until(new ExpectedCondition<WebElement>() {
        public WebElement apply(WebDriver d) {
            return d.findElement(By.linkText(""));
        }
    });

示例 B:

WebElement wer = new WebDriverWait(driver, 5).until((WebDriver dr1) -> dr1.findElement(By.id("q")));

示例 C:

(new WebDriverWait(driver(), 5)).until((driver) -> driver.findElement(By.linkText("Google")));

流畅等待

FluentWait is the implementation of the Wait 可以动态配置其超时和轮询间隔的接口。

每个 FluentWait 实例都定义了等待条件的最长时间,以及检查条件的频率。此外,用户可以配置等待以在等待时忽略特定类型的异常,例如在页面上搜索元素时 NoSuchElementExceptions

示例用法:

// Waiting 30 seconds for an element to be present on the page, checking for its presence once every 500 milliseconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(Duration.ofSeconds(30))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class);

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

Note: This class makes no thread safety guarantees.

您可以在讨论

中找到 FluentWait 的工作示例

你上面提到的两种方法的区别在于,第二种方法将在内存中创建一个额外的 class(也称为匿名内部 class),而第一种方法不会做这样的事。 如果确实需要“Function”接口的实现,创建一个 lambda 和上面提到的一样,你会看到同样的效果,在这种情况下它不会创建一个新的 Inner Class 实例。相反,将通过“InvokeDynamic”调用接口方法。