Fluent Wait - The Right Type of Lazy

There are usually many ways to solve a problem.The mental workout of finding good solutions to problems is probably one of the things that keeps me happy at work. I want to share one such example…

The problem is that our automated tests don’t behave consistently (for an unchanged target). The underlying issue is one of timing. The tests run at full speed and (sometimes) the application under test can’t keep up and assertions start to fail.

It’s not unreasonable to reason that the automated tests aren’t realistic. Users don’t work at full speed. However, the next link in that particular chain of thought is that you can just pepper your code with statements like:

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Don’t do this. I will think less of you.

The main problem with this approach is that you are merely increasing your chances of success (rather than ensuring success), at the cost of both performance and complexity.

There is a pattern called Fluent Wait (it’s used extensively behind the scenes in frameworks like Selenium) that provides a much better solution:

// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
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"));
}
});

No doubt many people would consider everything that I have said above to be obvious. I consider myself to be “the right type of lazy" (i.e. I want to make my life easier in the long run, even if it means extra work now) but there are still plenty of people in the workplace that are (in my view) “the wrong type of lazy" and they will ignorantly plaster over the cracks of life.

If you’re interested, there is a much more in-depth discussion of this topic (involving people much smarter than me) here:






comments powered by Disqus