2

I am not able to understand the use of new function() and apply() in the following code while learning timeouts using Fluent Wait method to set timeout in Selenium Webdriver script in java.

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

Could you please explain me the logic. Thanks.

  • How FluentWait is different from WebDriverWait? As I understand, WebDriverWait is the sub class of FluentWait. Which is preferred ? I am using WebDriverWait having polling interval set to 500 miliseconds. Still, the WebDriverWait takes few seconds (2-3) of time time to return (once the specified element is visible). Means, WebDriverWait is taking 2 to 3 seconds of time to return after the element is visible. Any opinion on this? Thanks, Dinesh – Dinesh Apr 30 '15 at 7:54
  • Please do not use Answers to ask new questions :) – Niels van Reijmersdal Apr 30 '15 at 8:20
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post. – Kate Paulk Apr 30 '15 at 10:41
3

What this does is, it waits until the element with id "foo" is found. If the element is not found, retry every 5 seconds. But wait only up to a maximum of 30 seconds.

It does this by calling the following function every 5 seconds, until it doesn't return null:

public WebElement apply(WebDriver driver) {
    return driver.findElement(By.id("foo"));
}

The whole "new Function" thingy creates an anonymous instance of an anonymous class.

The same can be achieved by writing something more or less like this:

class CheckForFoo implements Function<WebDriver,WebElement> {
    @override
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.id("foo"));
    }
}
...

...

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

Also see the definition of the Wait interface and the definition of FluentWait.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.