Saturday, November 7, 2015

WebDriverWait & ExpectedCondition

WebDriverWait & ExpectedCondition

The Selenium WebDriver provides an explicit wait for synchronizing tests, which provides a better control when compared with an implicit wait. Unlike an implicit wait, you can write custom code or conditions for wait before proceeding further in the code.

The Selenium WebDriver provides WebDriverWait and ExpectedCondition classes for implementing an explicit wait.

The ExpectedCondition class provides a set of predefined conditions to wait before proceeding further in the code. The following table shows some common conditions that we frequently come across when automating web browsers supported by the ExpectedCondition class:

Predefined condition Selenium method
Element value textToBePresentInElementValue(By locator, java.lang.String text)
Title titleContains(java.lang.String title)

For more on this please refer Selenium Testing Tools Cookbook by Unmesh Gundecha.

How WebDriverWait works

We can create a wait for a set of common conditions using the ExpectedCondition class. First, we need to create an instance of the WebDriverWait class by passing the driver instance and timeout for a wait as follows:

WebDriverWait wait = new WebDriverWait(driver, 10);

Next, ExpectedCondition is passed to the wait.until() method as follows:


The WebDriverWait object will call the ExpectedCondition class object every 500 millisecond until it return successfully. [Source: Selenium Testing Tools Cookbook by Unmesh Gundecha].

Example 1 of WebDriver Wait:

In this code we are opening After that we are writing text “Selenium” in google search field and clicking the Search button. Now after clicking on the Search button we are waiting for the link “Selenium - Web Browser Automation” to appear using WebDriverWait (and LinkText). After the link appears we click on the link to open the Selenium page. Now again we are waiting for the page to open using WebDriverWait (and XPath) before closing the browser.

Here you can have a list of all the ExpectedConditions which are generally useful within webDriver tests.

Example 2 of WebDriver Wait:

This example is similar to above (example 1) except that before closing the browser (at last) we are using Title.Contains instead of XPath (as in example 1).