10 coding watchouts for an Automation Developer – Part 2

Click here to read about 10 coding watchouts for an Automation Developer- Part 1

  1.  Wait

Loading a webpage can be affected through a number of parameters. There could be load or the code itself must be loading slowly. While loading a webpage, some of its elements may take a while to appear on the screen. This causes elementNotFound exception while trying to locate the element.

In such cases we usually use Thread.sleep() i.e. that will halt your execution for a specified amount of time.Now what if the element gets loaded before this time. So, using Thread.sleep() is never advisable in UI automation.

How to handle this problem?

There are 2 different way to handle this:

3.1 Implicit Waits:

It will always, and always look for that element for the specified period. If any element is not available within the specified time, it will throw a NoSuchElementException.

Here is an example:

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

In the above code snippet the webDriver will wait for 30 seconds to locate this element and if not found will throw NoSuchElementException.

The best example where you can use implicit waits is on a website’s homepage where you expect the page to load within a given time for better user experience.

3.2 Explicit Waits Unlike implicit waits, the explicit waits are applied to each and every webElement. The primary limitation of implicit wait is the fact that it only checks for the presence of web elements.

In explicit wait, certain conditions are defined for which the webDriver instance waits before locating webElements or performing actions on them.

Some of the most common conditions specified in explicit waits are- elementToBeClickable, presenceOfElementLocated etc. You can refer the Wrapper method’s example for explicit wait.

You would use Explicit waits in a case where for example you are expecting search results such as flight booking that takes time, to appear on screen.

  1.  Wrapper methods

Performing simulated actions on elements like click() and sendKeys() directly in script often leads to failures in case the elements on a webpage loads slowly.

While using implicit waits can help, the recommended solution is to use “Wrapper methods”. It makes the script not only readable but also stable and more maintainable.

I have created a wrapper method click() in an ‘elementController’ class that looks like this:

public static void click(WebDriver driver, By by) {

(new WebDriverWait(driver, 10)).until(ExpectedConditions.elementToBeClickable(by));



Now, every time I want to perform a click in my test I can simply call.

elementController.click(driver, By.id("buttonId");

This automatically performs a WebDriverWait, resulting in much stabler, better readable and maintainable script.

Click here for Part 3

Ravi Beck