【问题标题】:What is the difference between using lambda function in FluentWait usage and not using it?在 FluentWait 使用中使用 lambda 函数和不使用它有什么区别?
【发布时间】:2019-06-30 06:45:04
【问题描述】:

等待一个元素可以写成

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 表达式,函数式接口。但我没有完全明白。

【问题讨论】:

    标签: java selenium selenium-webdriver webdriverwait fluentwait


    【解决方案1】:

    WebDriverWait

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

    构造函数是:

    • WebDriverWait(WebDriver driver, java.time.Clock clock, Sleeper sleeper, long timeOutInSeconds, long sleepTimeOut)
    • WebDriverWait(WebDriver driver, long timeOutInSeconds):诱导此等待 将忽略在“直到”条件下默认遇到(抛出)的NotFoundException 实例,并立即传播所有其他实例。
    • WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis):诱导这个 Wait 将忽略在“直到”条件下默认遇到(抛出)的 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")));
    

    流利等待

    FluentWaitWait 接口的实现,可以动态配置其超时和轮询间隔。

    每个 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"));
        }
    });
    

    注意这个类不保证线程安全。

    您可以在讨论Selenium Webdriver 3.0.1: Selenium showing error for FluentWait Class

    中找到 FluentWait 的工作示例

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2021-11-29
        • 1970-01-01
        • 2021-09-27
        • 2014-12-21
        • 2019-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多