Using FluentWait Class to wait until a condition is true in Selenium Webdriver?



  • 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.



  • 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.



Suggested Topics

  • 2
  • 2
  • 3
  • 2
  • 2