Part 5: Waits In Selenium: What Happens When We Mix Sleep With Other Types Of Waits ?
Hello Folks,
In this post we will learn about behavior of webdriver when we mix waits together.
There are four types of waits in Selenium Webdriver. Those are:
Every wait has its own significance and we can use it in different scenarios. But what will happen or we can say in better way, “How webdriver will behave when we use different types of waits together?”.
Let’s think about it.
Mixing Thread.sleep() with any other waits:
- Thread.sleep() just holds the execution for specified time wherever you use this.
- If we use any other waits with sleep method, webdriver will just hold the execution for specified time and then will follow other wait.
- Sleep will not override any waits and vice-versa. For example, if we use sleep of 5 seconds and implicit wait as 30 seconds, in all scenarios webdriver will wait for minimum 5 seconds. Implicit wait will be applicable after that. We can say indirectly you have set time out as 5+30=35 seconds which is maximum and 5 seconds are minimum.
- Mixing sleep with any other waits will just increase your test execution time. We will understand this with below example:
Scenario:
- Open any browser.
- Load URL: :https://www.redbus.in/”
- Type “Ban” in From text box and wait till you get all results.
- Select Bangalore.
We define implicit wait and sleep together and assume all elements are available in DOM.
package MakeSeleniumEasy; import java.util.Date; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class SleepWithImplicitWait { public static void main(String[] args) throws InterruptedException { // Opening chrome browser System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe"); WebDriver driver= new ChromeDriver(); driver.manage().window().maximize(); // setting implicit time driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); // Loading a URL driver.get("https://www.redbus.in/"); // Locating and typing in From text box. WebElement fromTextBox= driver.findElement(By.id("src")); fromTextBox.sendKeys("Ban"); /* Since it is a search and choose text box, we need to wait till we get * all available options. We will use sleep and implicit wait together. */ System.out.println("Wait starts:"+new Date()); // Using sleep, we hold the execution Thread.sleep(5000); // Clicking on first search result driver.findElement(By.xpath("//li[@select-id='results[0]']")).click(); System.out.println("Selected Bangalore"); System.out.println("Wait ends:"+new Date()); //Closing browser driver.quit(); System.out.println("browser closed"); } }
Output:
Wait starts:Fri Jun 23 22:41:25 IST 2017 Selected Bangalore Wait ends:Fri Jun 23 22:41:31 IST 2017
browser closed