The Selenium WebDriver provides an explicit wait for synchronizing tests, which provides a better way to wait over an implicit wait. Unlike an implicit wait, you can write and use pre-defined conditions or custom conditions for wait before proceeding further in the code.
The Selenium WebDriver provides the WebDriverWait
and ExpectedConditions
classes to implement an explicit wait.
The ExpectedConditions
class provides a set of predefined conditions to wait for 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 ExpectedConditions
class:
Predefined condition |
Selenium method |
---|---|
An element is visible and enabled |
|
An element is selected |
|
Presence of an element |
|
Specific text present in an element |
|
Element value |
|
Title |
|
For more conditions, visit http://seleniumhq.github.io/selenium/docs/api/java/index.html.
In this recipe, we will explore some of these conditions with the WebDriverWait
class.
Let's implement a test that uses the ExpectedConditions.titleContains()
method to implement an explicit wait, as follows:
@Test public void testExplicitWaitTitleContains() { //Go to the Google Home Page WebDriver driver = new FirefoxDriver(); driver.get("http://www.google.com"); //Enter a term to search and submit WebElement query = driver.findElement(By.name("q")); query.sendKeys("selenium"); query.click(); //Create Wait using WebDriverWait. //This will wait for 10 seconds for timeout before title is updated with search term //If title is updated in specified time limit test will move to the text step //instead of waiting for 10 seconds WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.titleContains("selenium")); //Verify Title assertTrue(driver.getTitle().toLowerCase().startsWith("selenium")); driver.quit(); }
We can define an explicit wait for a set of common conditions using the ExpectedConditions
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, the ExpectedCondition
is passed to the wait.until()
method, as follows:
wait.until(ExpectedConditions.titleContains("selenium"));
The WebDriverWait
object will call the ExpectedConditions
class object every 500 milliseconds until it returns successfully.
3.21.12.140