What is Synchronization in Selenium? How to Achieve Synchronization in Selenium?

 What is Synchronization ?
When two or more components work together, they should work in sync in order to achieve the desired result. If those components are not working in parallel or in sync, you may not get expected result. So, working of those components in sync or in parallel is termed as Synchronization.
In case of selenium test automation, there are two things who should work in parallel or in sync.
            1.       Application Under Test (AUT)
            2.       Testing tool (here, let us consider as Selenium)
Now, both of these two things (AUT & Selenium) have their own speed. Selenium Webdriver may be faster, but in some of the cases, application under test, takes some time for page load, or for web elements to be present on the webpage. In this case, Selenium Webdriver may not find those elements since the speed of Selenium Webdriver is faster as compare to Application (suppose). So here your tests will fail.
In order to overcome this situation, Application Under Test (website that you are testing) and your testing tool (Selenium in this case) should have same working speed. So, to match the speed of the application or in some case, to wait for specific conditions at some point of time, we use Synchronization, which helps to bring the AUT & Testing tool speed in sync. Now “Element Not Found” Error may not arise.
One of the way to implement wait is by calling thread.sleep() function however, it is not recommended because this is not very stable and unreliable. The time has to be specified in milliseconds.

There are 2 ways to Achieve Synchronization.
             1.       Implicit wait
             2.       Explicit wait
To understand about types of the wait, below links describe the Implicit and Explicit wait in more details –

Why not to use Thread.sleep(); toachieve synchronization in selenium?

What is Implicit wait? How to Achieve Implicit wait in Selenium?

What is Explicit wait? How to Achieve Explicit wait in Selenium?

What is Fluent wait? How to Achieve Fluent wait inSelenium?

Which is the best wait in selenium WebDriver?

 

Hope This Helps !!!!!

Which is the best wait in selenium WebDriver?

best wait??

To answer which wait to use will be very specific because the answer may change depending on the Web-element you are focusing, Platform and many more.
According to me, Best wait is Fluent Wait because
  1. It works as per customized condition required at run time.
  2. It gives an option to user to change poll time i.e. At which frequency Dom is to be polled for checking element presence.
  3. It also gives option to ignore any specific exception while searching which may not be related to search but hinder our search resulting in exception or unoptimized search.
  4. Provides better support with JavaScript elements which are attached to DOM but are invisible.
  5. Provides better support to Ajax applications​ as it has option to ignore specific exceptions during element search.

What is Fluentwait? How to Achieve Fluent wait in Selenium?

FluentWait in Selenium WebDriverFluentWait is a customized type of Explicit Wait, here we can define polling period according to our need 2 Secs or 5 Secs, We can also configure the wait to ignore some exceptions like NoSuchElementExceptions.

This wait will check for the elements in the DOM for every 5 Secs until the elements found, if the element found within the period it breaks the search for the element and goes for the further action.

Fluent wait = Explicit Wait + frequency with which control need to be checked on application + exceptions to be ignored like  NoSuchElementExceptions.

Syntax: 
 

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
//Wait for the condition
.withTimeout(30, TimeUnit.SECONDS)
// which to check for the condition with interval of 5 seconds.
.pollingEvery(5, TimeUnit.SECONDS)
//Which will ignore the NoSuchElementException
.ignoring(NoSuchElementException.class);

Features of Fluent Wait:

In Fluent Wait we define a Maximum amount of time to wait for a condition. Also, we will be defining a Polling frequency time while declaring the Fluent Wait.Fluent Wait will be polling the web pages every Polling frequency time to verify the given condition.

Fluent Wait has Inbuilt exception handler, which will handle NoSuchElementException until given Maximum amount of time has breached.

Refer below Example for Fluent Wait –

package demoPackage1;

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

import javax.lang.model.element.Element;

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.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.testng.annotations.Test;

import com.google.common.base.Function;


public class ExplicitWait {

  @Test
  public void FluentWaitTest(){
    
    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    
    driver.navigate().to("http://demowebshop.tricentis.com");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    
       // Define fluent wait
       Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
           .withTimeout(30, TimeUnit.SECONDS)
           .pollingEvery(1, TimeUnit.SECONDS)
           .ignoring(NoSuchElementException.class);

       WebElement element = wait.until(new Function<WebDriver, WebElement>() 
       {
         public WebElement apply(WebDriver driver) { 
           return driver.findElement(By.xpath("//a[@class='ico-register']"));
         } } );
       element.click();
    
    driver.close();
    driver.quit();
  }
}

FluentWait in Selenium WebDriver

What is Explicit wait? How to Achieve Explicit wait in Selenium?

What is Explicit wait in Selenium WebDriver?

 

Explicit wait is a type of synchronization in selenium, which is webelement specific and not applied to driver for his life. Different elements on the page takes different times to load on the page, if we use implicit wait for 10 Sec there is no guarantee that all the elements loaded within 10 sec, some elements may take more than 1 minute, in such conditions Explicit waits can be used to wait for that particular element.
Explicit Wait in-Selenium-Webdriver
We can tell the tool to wait only till the Condition satisfy. Once the condition is satisfying, the tool proceed with the next step. This can be done with WebDriverWait in conjunction with ExpectedConditions Class.
Logic: –
It is applicable to the given control and waits to the maximum amount of time or move forward in case the given condition is met.

We are explicitly making the execution of selenium code to wait, for a certain condition to occur before, proceeding further in the code.

Syntax:

WebDriverWait.until(condition-that-finds-the-element(ExpectedCondition))

WebDriverWait by default calls the Expected Condition every 500 milliseconds until it returns successfully. Expected condition can be in the form of like:
button is disabled/enabled
textbox is visible
alertispresentExample for Explicit Wait

package demoPackage1;

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

public class ExplicitWait {

  @Test
  public void ExplicitWaitTest(){
    
    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    
    driver.navigate().to("http://demowebshop.tricentis.com/register");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    
    //define webdriver wait statement with time specified
    WebDriverWait wait = new WebDriverWait(driver, 10);
    
    //apply the wait for specific element. Below statement will wait for element to be present till 10 sec as specified by above
    wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy((By.xpath("//a[@class='ico-register']"))));
    
    driver.close();
    driver.quit();
  }
}

 

Explicit Wait in Selenium WebDriver

Hope This Helps !!!!

What is Implicit wait? How to Achieve Implicit wait in Selenium?

What is Implicit wait in Selenium WebDriver?

It means that we can tell Selenium that we would like it to wait for a certain amount of time before throwing an exception (when it cannot find the element on the page).

synchronization in selenium webdriver - Implicit wait

For example:

driver.manage().timeouts().pageLoadTimeout(50,TimeUnit.SECONDS);
 
Above statement will set the navigation timeout as 50. This means that selenium script will wait for maximum 50 seconds for page to load. If page does not load within 50 seconds, it will throw an exception.
The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
Syntax:
 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when the 30 seconds have elapsed after executing the previous test step/command.

Logic: – Selenium checks the control in first go, in case it is not able to find the control it will wait for the given implicit time, and then try again, after the end of the wait time to look for the control before throwing an exception. By default, its value is 0.

Limitation: – implicit wait will be applied to all the elements of the test case by default.

Key Notes

  • Implicit wait is a single line of a code and can be declared in the setup method of the test script.
  • When compared to Explicit wait, Implicit wait is transparent and uncomplicated. The syntax and approach is simpler than explicit wait.
  • Implicit wait will not work all the commands/statements in the application. It will work only for “FindElement” and “FindElements” statements
Being easy and simple to apply, implicit wait introduces a few drawbacks as well. It gives rise to the test script execution time as each of the command would be ceased to wait for a stipulated amount of time before resuming the execution.
Thus, in order to trouble shoot this issue, WebDriver introduces Explicit waits where we can explicitly apply waits whenever the situation arises instead of forcefully waiting while executing each of the test steps.

Example for Implicit Wait

WebDriver driver = new FirefoxDiriver();

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

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

 

Refer below video –

Why not to use Thread.sleep(); to achieve synchronization in selenium?

thread.sleep() in selenium
One of the way to achieve synchronization, implement wait is by calling Thread.sleep() function however, it is not recommended because this is not very stable and unreliable. The time has to be specified in milliseconds.
I think Thread.sleep() is considered as the worst case of explicit wait because, for Thread.sleep(), it has to wait for the full time specified as the argument of Thread.sleep(), before proceeding further.
it is not related to Implicit wait or Explicit wait…So we should not be confused due to resemblance in Sync method in Selenium and Thread.sleep.
The main disadvantage for Thread.sleep;statement is, there is a chance of unnecessary waiting time even though the application is ready.
We can achieve synchronization using Thread.Sleep, method of Java. However this is not recommended methodology. As it is same like asking selenium to stop executing for given X milliseconds so that our control is loaded and it is not guaranteed that within that hard coded X value, control is fully loaded and our test code can execute safely.
Ex: Thread. Sleep (20000);
Here the execution is halted for 20 Sec., even if the object we are looking exists at that instant, so it unnecessary waits of 20 sec.
or
Control exists after 10 sec. So here also selenium unnecessarily waits for more 10 sec.

Refer below posts to understand more about various types of synchronization.

Hope this helps.