top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-
Writer's pictureRajalakshmi KR

Synchronization in Selenium

Synchronization is the most important concept in Automation. First let’s understand the meaning of word “Synchronization”. According to Wikipedia, “Synchronization" is the coordination of events to operate a system in unison.




Similarly in automation, the code execution and the application which is under test needs to be in sync to perform operation without any exception. Application and code should go hand in hand without any halt or pause to achieve successful testing of the application.

Applications may slow down for various reasons like network, heavy data load, hardware issues, server down etc., then test script keeps on looking for particular web element and if the code does not find that element at that moment while executing, the code fail by throwing exceptions. Some exceptions are

NoSuchElementException

ElementNotVisibleException

NoSuchFrameException

NoAlertPresentException

NoSuchWindowException

SessionNotFoundException

StaleElementReferenceException

InvalidSelectorException

In order to avoid the halt or failure of test cases due to exceptions, testers should write a code which synchronizes with the application. In Selenium Web automation, synchronization can be handled using wait command.

Synchronization are of two types:

· Unconditional

· Conditional


Unconditional Synchronization:

In unconditional Synchronization, the tester has to explicitly specify timeout value which will make the automation tool to wait for certain period of time and then proceed further. Unconditional Synchronization is also known as static wait.


Examples:

1. Thread.sleep(2000);

This pauses the test execution for 2000 milliseconds

2. Wait();

While using this method, we may get InterruptedException which has to be handled either by using throws or try catch block as shown below

try{

Thread.sleep (2000);

}

Catch(InterruptedException ie)

}

Or

public static void main (String args []) throws InterruptedException {

Thread.sleep (2000);

}

The main disadvantage of using thread statement is that there is lot of unnecessary waiting time even though the application is ready for execution and the element is found in DOM.


When our automation tool has to integrate with third party interfaces, it is not possible to write a condition or check for any existing condition. In this scenario, we can use unconditional synchronization. As the name suggests, we do not have specify any condition while executing the scripts, we just specify pause or halt duration. Hence it is called as static wait.


Let me relate the above method by simple bus example. Suppose I have to travel from Atlanta to New York, I catch the bus at Atlanta bus station with 4 stops in between until I reach New York. The bus starts from Atlanta and stops or halts 10 minutes in each stop, the passengers get in or get out and the bus moves on further. In each stop the process repeats until I reach New York. Here we can correlate the bus journey as running scripts and 10 min halts is like a thread which will pause for 10 minutes.


wait() method is a part of java.lang.Object class. When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread.


Syntax:

public final void wait() throws InterruptedException

Basically both wait() and Thread.sleep() are mostly used in Java rather than Selenium automation. It is good practice to used conditional synchronization in selenium automation which I have described below.


Conditional Synchronization:

In conditional synchronization, the tester specifies the timeout duration along with some desired conditions to check and then throw an error if nothing happens. Conditional synchronization is also known as Dynamic wait. It is very important to set the timeout value in this type because the automation tool should proceed further instead of making the tool to wait for a particular condition to satisfy.

There are mainly two types of conditional synchronization:

Implicit wait and Explicit wait


Implicit Wait:

This wait in selenium is used to tell the web driver to wait for a certain amount of time before it throws a “No Such Element Exception”. The default setting is 0. Once the tester sets the time, the web driver will wait for the element for that time before throwing an exception. Once the command is in place, Implicit Wait stays in place for the entire duration for which the browser is open. It is like one definition which is used throughout the test script.


Syntax:


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


To add implicit waits in test scripts, we need to import the below package:


Import java.util.concurrent.TimeUnit;


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


In the above line, timeout value is set to 20 seconds, which means that if an element is not located on the web page within that time frame, it throws an exception. Implicit wait will accept 2 parameters, the first parameter will accept the time as an integer value and the second parameter will accept the time measurement in terms of Seconds, Minutes, Milliseconds, Microseconds, Nanoseconds, Days, and Hours etc.


Implicit wait increases test script execution time. It makes each command wait for the defined time before resuming test execution. If the application responds normally, the implicit wait can slow down the execution of test scripts which impacts the test performance.

Implicit wait is like a global wait, it is always available for all the elements through the web driver instance.


Explicit Wait:

In explicit wait, we explicitly specify the condition and timeout so that the script does not throw an exception. The WebDriver is directed to wait until a certain condition occurs before proceeding with executing the code. Setting Explicit Wait is important in cases where there are certain elements that naturally takes more time to load. Explicit wait is more refined, it is not set globally unlike implicit wait. It is specific to one particular element in the DOM.

Explicit wait is more intelligent, but can only be applied for specified elements. However, it is an improvement on implicit wait since it allows the program to pause for dynamically loaded Ajax elements. It saves time and improves test performance.

In order to declare explicit wait, one has to use “ExpectedConditions”. The following Expected Conditions can be used in Explicit Wait


· alertIsPresent()

· elementSelectionStateToBe()

· elementToBeClickable()

· elementToBeSelected()

· frameToBeAvaliableAndSwitchToIt()

· invisibilityOfTheElementLocated()

· invisibilityOfElementWithText()

· presenceOfAllElementsLocatedBy()

· presenceOfElementLocated()

· textToBePresentInElement()

· textToBePresentInElementLocated()

· textToBePresentInElementValue()

· titleContains()

· visibilityOf()

· visibilityOfAllElements()

· visibilityOfAllElementsLocatedBy()

· visibilityOfElementLocated()


The following packages needs to be imported to implement explicit wait:


Import org.openqa.selenium.support.ui.ExpectedConditions

Import org.openqa.selenium.support.ui.WebDriverWait


Then, Initialize a Wait Object using WebDriverWait Class.


WebDriverwait wait=new WebDriverWait (driver, 20);


Here, the reference variable is named <wait> for the <WebDriverWait> class. It is instantiated using the WebDriver instance. The maximum wait time must be set for the execution to layoff. Wait time is measured in seconds.


WebDriverWait wait = new WebDriverWait (driver,20);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(“//*[contains(text(),’GetStarted’)]”))); //button click


If we use the above line of code, the web driver waits for 20 seconds before throwing “Timeout Exception” and if it finds element within the time frame, it returns immediately.

After that, it will click on the “Get Started” button. In this case, the program will not wait for the entire 20 seconds, thus saving time and executing the script faster.


Let’s see some of the difference between implicit and explicit wait:

Implicit Wait

Explicit Wait

Applies to all elements in a test script.

Applies only to specific elements as written by tester

Expected conditions not specified

ExpectedConditions is required for the element which needs to be located in DOM

It is simple and easy to implement.

It is has more complex implementation compared to implicit wait.

Does not catch performance issues of the application

Catches the performance issues of the application

Conclusion:

In this blog, I have briefly explained the synchronization types with different waits in Selenium. Hope it is helpful.


Thank you for reading.

42 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page