SYNCHRONIZATION

 

 To synchronize between script execution and application, we need to wait after performing appropriate actions. Let us look at the ways to achieve the same.

THREAD.SLEEP

Thread.Sleep is a static wait and it is not a good way to use in scripts as it is sleep without condition.

Syntax:

Thread.Sleep(3000);  

// will wait for three seconds. 

EXPLICIT WAIT

An 'explicit wait,' waits for a certain condition to occur before proceeding further. It is mainly used when we want to click or act on an object once it is visible.

Syntax:

WebDriver driver - new FirefoxDriver();

driver.get("aramkrishna.blogspot.com");

WebElement ew=(new WebDriverWait(driver, 10).

until(expectedCondition.presenceofElementlocated(by.id("ramakrishna")));

IMPLICIT WAIT

Implicit wait is used in cases where the WebDriver cannot locate an object immediately because of its unavailability. The WebDriver will wait for a specified implicit wait time and it will not try to find the element again during the specified time period.

Once the specified time limit is crossed, the webDriver will try to search the element once again for one last time. Upon success, it proceeds with the execution; upon failure, it throws exception.

It is a kind of global wait which means the wait is applicable for the entire driver. Hence, hardcoding this wait for longer time periods will hamper the execution time

Syntax: 

WebDriver driver=new FirefoxDriver();

driver .get("aramkrishna.blogspot.com");

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

WebElement iw=driver.findElement(By.id("ramakrishna"));

FLUENT WAIT

A Fluent Wait instance defines the maximum amount of time to wait for a condition to take place, as well as the frequency with which to check the existence of the object condition.

Let us say we will 60 seconds for an element to be available on the page, but we will check its available once in every 10 seconds.

Syntax:

Wait wait=

new FluentWait(driver).WithTimeout(60, secounds).

pollingEvery(10, secounds).

ignoring(noSuchElementException.class);


WebElement fw =

 wait.until(newFunction<webdriver, webElement>() {


public webElement apply(webDriver) {


return driver.findElement(By.id("ramakrishna"));

}

});