Earlier versions of WebDriver used a FluentWait
class, the WebDriverWait
now offers a fluent DSL approach for configuring the wait.
My synchronisation strategies with WebDriver have generally revolved around the WebDriverWait and creating custom ExpectedCondition objects.
A traditional basic use of WebDriverWait
uses minimal customisation, because most of the defaults are good enough for our use.
e.g
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.
elementToBeClickable(
By.id("htmlformtest")));
driver.findElement(By.id("htmlformtest")).click();
Fluent Interface
A basic wait, is already fluent and we can chain the methods:
new WebDriverWait(driver, 10)
.until(ExpectedConditions.elementToBeClickable(
By.id("htmlformtest")))
.click();
This doesn’t mean that the code is easier to read or maintain, because it might be better to re-use the wait later in the test.
But the fluent interface allows us to use code completion to build it up.
The fluent interface goes beyond the simple use case allowing us to configure the wait.
FluentWait
WebDriverWait
extends a FluentWait
class.
FluentWait
can be useful for waiting on ‘anything’ and we cover that in our Synchronisation Course.
Allowing us to chain methods to configure
withTimeout
how long before timeoutwithMessage
the message to display when it timesoutpollingEvery
how long between polling intervalsignoreAll
,ignoring
which exceptions to ignore during the polling
All of the above methods can be ‘chained’ to create a fluent configuration of a WebDriverWait
Example
The code waits for the element to become visible using a WebDriverWait then drops down to a lower level of granularity to check that the seconds count down to 04
driver.get("https://testpages.herokuapp.com/styled/"+
"javascript-countdown-test.html");
By countdown = By.id("javascript_countdown_time");
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until( ExpectedConditions.
visibilityOfElementLocated(countdown));
wait.withTimeout(Duration.ofSeconds(30)).
pollingEvery(Duration.ofMillis(500)).
until(ExpectedConditions.textMatches(
countdown, Pattern.compile(".*:04$")) );
The additional configuration offered by Fluent configuration of a WebDriverWait
can prove pretty handy for Ajax because of the flexibility you have for ignoring exceptions and easily tweaking the wait and polling times.
Full Source
The full source for this is in my Webdriver Java FAQs project:
Specifically:
If you want to learn how to use Selenium WebDriver with Java then check out our online courses. And we have a whole course on effective synchronisation strategies.