Annoucement: New Java and Selenium batch is starting from October 28th Nov, Please enroll ASAP!

Difference between ImplicitWait, ExplicitWait, FluentWait, PageLoadTimeOut and Thread.sleep in Selenium WebDriver

Difference between ImplicitWait, ExplicitWait, FluentWait, PageLoadTimeOut and Thread.sleep in Selenium WebDriver



Synchronization in Selenium WebDriver:



1.What is Synchronization.
2.Why Synchronization is required.
3.When Synchronization is required.
4.Conditional and Unconditional Synchronization in Selenium WebDriver.




It is a mechanism which involves more than one components to work parallel with Each other.

Generally in Test Automation, we have two components
1. Application Under Test.
2. Test Automation Tool.


Both these components will have their own speed. We should write our scripts in such a way that both the components should move with same and desired speed, so that we will not encounter "Element Not Found" errors which will consume time again in debugging.
It is a process of coordinating or matching two or more activities/devices/processes in time.
Process of matching the speed of AUT(Application under test) & Test tool in order to get proper execution.
During the test execution Test tool gives instructions one by one with same speed, but AUT takes less time for some steps execution and more time for some steps execution, in order to keep them in sync then Synchronization is required.
Whenever any step required time more than Synchronization time for execution, then Synchronization is required. 






Thread.Sleep:
Thread.sleep method is used to pause the execution for defined time. Time is defined in milliseconds for this method.
Implicit Wait: 
During Implicit wait if the Web Driver cannot find it immediately because of its availability, it will keep polling the DOM to get the element.
If the element is not available within the specified Time an NoSuchElementException will be raised.
The default setting is zero.
Once we set a time, the Web Driver waits for the period of the WebDriver object instance.
Explicit Wait:  
There can be instance when a particular element takes more than a minute to load.
In that case you definitely not like to set a huge time to Implicit wait, as if you do this your browser will going to wait for the same time for every element.
To avoid that situation you can simply put a separate time on the required element only.
By following this your browser implicit wait time would be short for every element and it would be large for specific element.
Fluent Wait: 
Let’s say you have an element which sometime appears in just 1 second and some time it takes minutes to appear.
In that case it is better to use fluent wait with polling mechanism, as this will try to find element again and again until it finds it or until the final timer runs out.
It tries to find the web element repeatedly at regular intervals(as specified in polling period) of time until the timeout or till the object gets found. It can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.
Page Load Time Out:
The pageLoadTimeout limits the time that the script allots for a web page to be displayed.
If the page loads within the time then the script continues.
If the page does not load within the timeout the script will be stopped by a TimeoutException.


ExplicitWait.java


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

public class ExplicitWait {

 static WebDriver driver;

 @Test
 public void main() throws InterruptedException {
  System.setProperty("webdriver.chrome.driver",
    System.getProperty("user.dir") + "/src/main/resources/chromedriver");
  driver = new ChromeDriver();

  driver.get("http://the-internet.herokuapp.com/dynamic_loading/1");

  driver.findElement(By.xpath("//button[text()='Start']")).click();
  WebElement content = driver.findElement(By.xpath("//h4[text()='Hello World!']"));

  // Explicit Wait
  WebDriverWait explicitWait = new WebDriverWait(driver, 10);
  explicitWait.until(ExpectedConditions.visibilityOf(content));

  Assert.assertTrue(content.isDisplayed(), "Content is not displayed");
  System.out.println(content.getText());

 }
 
 @AfterTest
 public void close() {
  driver.quit();
 }

}


FluentWait.java


import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

public class FluentWait1 {

 static WebDriver driver;

 @Test
 public void main() throws InterruptedException {
  System.setProperty("webdriver.chrome.driver",
    System.getProperty("user.dir") + "/src/main/resources/chromedriver");
  driver = new ChromeDriver();

  driver.get("http://the-internet.herokuapp.com/dynamic_loading/1");

  driver.findElement(By.xpath("//button[text()='Start']")).click();

  // Fluent Wait
  Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)

    .withTimeout(30, TimeUnit.SECONDS)

    .pollingEvery(1, TimeUnit.SECONDS)

    .ignoring(NoSuchElementException.class);

  WebElement content = fluentWait.until(new Function<WebDriver, WebElement>() {
   public WebElement apply(WebDriver driver) {
    return driver.findElement(By.xpath("//h4[text()='Hello World!']"));
   }
  });

  System.out.println(content.getText());
 }
 
 @AfterTest
 public void close() {
  driver.quit();
 }

}


ImplicitWait.java


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;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

public class ImplicitWait {

 static WebDriver driver;

 @Test
 public void main() throws InterruptedException {
  System.setProperty("webdriver.chrome.driver",
    System.getProperty("user.dir") + "/src/main/resources/chromedriver");
  driver = new ChromeDriver();

  // Implicit Wait
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

  driver.get("http://the-internet.herokuapp.com/dynamic_controls");

  driver.findElement(By.xpath("//button[@id='btn']")).click();

  WebElement checkBox = driver.findElement(By.xpath("//input[@id='checkbox']"));

  Assert.assertTrue(checkBox.isDisplayed(), "checkBox is not displayed");

  driver.findElement(By.xpath("//button[text()='Remove']")).click();

  WebElement message = driver.findElement(By.id("message"));

  Assert.assertTrue(message.isDisplayed(), "Message is not displayed");

 }

 @AfterTest
 public void close() {
  driver.quit();
 }

}


PageLoadTimeOut.java


import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

public class PageLoadTimeOut {

 static WebDriver driver;

 @Test
 public void main() {
  System.setProperty("webdriver.chrome.driver",
    System.getProperty("user.dir") + "/src/main/resources/chromedriver");
  driver = new ChromeDriver();

  // Page Load Time Out
  driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.MILLISECONDS);

  driver.get("http://the-internet.herokuapp.com/dynamic_loading/1");

 }

 @AfterTest
 public void close() {
  driver.quit();
 }

}


ThreadSleep.java



import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

public class ThreadSleep {

 static WebDriver driver;

 @Test
 public void main() throws InterruptedException {
  System.setProperty("webdriver.chrome.driver",
    System.getProperty("user.dir") + "/src/main/resources/chromedriver");
  driver = new ChromeDriver();

  driver.get("http://the-internet.herokuapp.com/dynamic_controls");

  driver.findElement(By.xpath("//button[@id='btn']")).click();

  
  
  // Thread.Sleep()
  Thread.sleep(1000);

  WebElement checkBox = driver.findElement(By.xpath("//input[@id='checkbox']"));

  Assert.assertTrue(checkBox.isDisplayed(), "checkBox is not displayed");

  driver.findElement(By.xpath("//button[text()='Remove']")).click();


  
  // Thread.Sleep()
  Thread.sleep(10000);

  WebElement message = driver.findElement(By.id("message"));

  Assert.assertTrue(message.isDisplayed(), "Message is not displayed");

 }
 
 @AfterTest
 public void close() {
  driver.quit();
 }

}


(Synchronization with all types of waits in WebDriver)

Synchronization.java


import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Synchronization {

 static WebDriver driver;

 public static void main(String[] args) throws InterruptedException {
  System.setProperty("webdriver.chrome.driver",
    System.getProperty("user.dir") + "/src/main/resources/chromedriver");
  driver = new ChromeDriver();
  
  
  // Page Load Time Out
  driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);

  // Implicit Wait
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

  // Explicit Wait
  WebDriverWait explicitWait = new WebDriverWait(driver, 30);
  explicitWait.until(ExpectedConditions.visibilityOfElementLocated(By.id("id")));

  // Fluent Wait
  Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)

    // Waiting 30 seconds for an element to be present on the page, checking
    .withTimeout(30, TimeUnit.SECONDS)

    // for its presence once every 5 seconds.
    .pollingEvery(5, TimeUnit.SECONDS)

    .ignoring(NoSuchElementException.class);

  // Thread.sleep()
  Thread.sleep(3000);

  driver.get("http://www.google.com");

 }

}

12 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
    Replies
    1. Ni, It actually polls internally until the element is found in the html DOM within the given time. This is the correct behavior of implicit wait.

      Delete
    2. Hi Naveen,

      When you say its waits until the element is found in the html DOM . So, Does it check for all the web elements ?

      and what is the difference b/w the Implicit and pageloadtimeout wait?

      Delete
  2. Naveen sir, can you please clarify if by default ImpliciteWait try to poll on all WebElements on every page? If we use it where driver initialization takes place in our framework.

    ReplyDelete
  3. Hi Naveen,

    Below is my code for clciking SignUp link on FreeCRM.com. Its working using Thread.sleep() but not by any other wait. Can you please suggest how to avoid Thread.Sleep() here:

    public static void main(String[] args) {
    Selenium s = new Selenium();
    s.launchBrowser();
    //Thread.sleep(2000);
    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.elementToBeClickable((driver.findElement(By.linkText("Sign Up"))))).click();
    s.signUpPage();
    driver.quit();
    }

    ReplyDelete
  4. Hi Naveen,
    Below is my code to select a value form autosuggestive dropdown,
    However, I am unable to click on the selected element in dropdown.
    Also my id value,in the span class changes for every search.

    Request to please help me out.
    Thanks
    -----------------------------------------------

    public class Autosuggestive {

    public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    System.setProperty("webdriver.chrome.driver", "C:\\Data\\Selenium\\chromedriver (2).exe");

    WebDriver driver= new ChromeDriver();

    driver.manage().window().maximize();

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    driver.get("https://ptv.vic.gov.au");

    driver.findElement(By.linkText("Timetables")).click();

    Select s = new Select(driver.findElement(By.id("Form_ModeSearchForm_Mode")));

    s.selectByValue("1");

    driver.findElement(By.xpath("//input[@id='Form_ModeSearchForm_Search']")).sendKeys("south");

    List list=driver.findElements(By.xpath("//ul[@id='ui-id-1']/li/descendant::span[@id='ui-id-2']"));

    System.out.println("Total number of suggestions are : "+list.size());
    for (int i=0;i<list.size();i++)
    {
    System.out.println(list.get(i).getText());
    if(list.get(i).getText().contains("yarra)"))
    {
    list.get(i).click();
    break;
    }
    }
    driver.findElement(By.cssSelector("input[id='Form_ModeSearchForm_action_doModeSearch']")).click();



    }


    }

    ReplyDelete

  5. Pretty blog, so many ideas in a single site, thanks for the informative article, keep updating more article.
    Webdesining course in chennai

    ReplyDelete
  6. Naveen bro please tell me difference between pageloadtimeout and implicitly wait

    ReplyDelete
  7. do you think this is valid -

    WebElement message = driver.findElement(By.id("message"));
    Assert.assertTrue(message.isDisplayed(), "Message is not displayed");


    check again ...

    ReplyDelete
  8. Hi Naveen,

    Can you please elaborate the difference between implicit wait and fluent wait. In both the cases, we are polling upto a maximum time, so what is the actual need for fluent wait.

    Thanks in advance :)

    ReplyDelete
  9. I agree with a lot of the points you made in this article. If you are looking for the Back Pain Pillow, then visit Eliterest. I appreciate the work you have put into this and hope you continue writing on this subject.

    ReplyDelete

Featured Post

How to control Chromedriver using curl

How to control Chromedriver using curl Here is how to use Chromedriver without libraries like  selenium-webdriver . This can be useful ...