Reduce the explicit waits duplicated code with a custom driver class

Alex Siminiuc
3 min readJul 12, 2022

Any Selenium test automation code should synchronize with the page by waiting for an element to be present with a specific state (enabled, visible, hidden) before the element is used.

This is done with explicit waits and expected conditions (not with implicit waits) as follows:

WebDriverWait wait = new WebDriverWait(driver, 30);wait.until(ExpectedConditions.visibilityOfElementLocated(loc));
WebElement element = driver.findElement(loc);

Or

WebDriverWait wait = new WebDriverWait(driver, 30);WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(loc));

The problem with synchronization is that it needs to be done every time an interaction with an element is needed. This generates a lot of duplicated code which we should do something about.

How can we remove the duplicated code?

One way of removing the duplicated code would be by creating a utility class with static methods and adding a static method in it for finding an element:

public static WebElement findElement(By loc, WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 30);
return wait.until(
ExpectedConditions.visibilityOfElementLocated(loc));
}

--

--