Wednesday, October 29, 2014

Chapter 23- Synchronization

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 good way to use in script as it's sleep without condition.
Thread.Sleep(1000); //Will wait for 1 second.

EXPLICIT WAITS

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 object once it is visible.
WebDriver driver = new FirefoxDriver();
driver.get("Enter an URL"S);
WebElement DynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("DynamicElement")));

IMPLICIT WAIT

Implicit wait is used, if Web Driver cannot find the object immediately because of its unavailability. The WebDriver will wait for 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, webdriver will try to search the element once again for one last time. If succeeds proceeds with the execution but if failed it throws exception. This is kind of global wait which means this wait is applicable for the entire driver. Hence hardcoding this wait for longer timeperiod will hamper the script execution time.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("Enter an URL");
WebElement DynamicElement = driver.findElement(By.id("DynamicElement"));

FLUENT WAIT

FluentWait is used when a webelement can appear in 5 seconds or even it can take 90 seconds. In such instance we define the maximum amount of time to wait for a condition, as well as the frequency with which to check the existance of the object condition.
Let us say we will 60 seconds for an element to be available on the page but checking its presence once in every 10 seconds.
Wait wait = new FluentWait(driver)
  .withTimeout(60, SECONDS)
  .pollingEvery(10, SECONDS)
  .ignoring(NoSuchElementException.class);
WebElement dynamicelement = wait.until(new Function<webdriver,webElement>() 
{
  public WebElement apply(WebDriver driver) 
  {
  return driver.findElement(By.id("dynamicelement"));
  }
 }
);


No comments: