Synchronization
Synchronization:
Generally in Test Automation, we have two components: Application Under Test and 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.
So, Matching of test script execution speed with application speed or browser speed is known as synchronization.
Ways to achieve Synchronization:
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 number of milliseconds so that our control is loaded.
The main disadvantage for Thread.sleep;statement is, there is a chance of unnecessary waiting time even though the application is ready.
Syntax
Thread.Sleep(2000); //Will wait for 2 second.
Implicit Wait means we 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).
If we set implicit wait, find element will not throw an exception if the element is not found in first instance, instead it will poll for the element until the timeout and then proceeds further.
It is a mechanism which will be written once and applied for entire session automatically. It should be applied immediately once we initiate the Webdriver.
Syntax
driver.manage.timeouts.implicitwait(10,Timeunit.SECONDS);
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // Will wait for 20 seconds.
driver.get("http://www.google.com");
By using Explicit Wait, We can wait till the Condition satisfy. Once the condition is satisfying, then proceed with the next step. It is mainly used when we want to click or act on an object once it is visible.
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath of that element")));
Using FluentWait we can define the maximum amount of time to wait for a condition, as well as the frequency with which to check for the condition.
For Example- There will be 50 seconds for an element to be available on the page, but we will check its avilable once in every 5 seconds.
Wait wait =
new FluentWait(driver).withTimeout(50, SECONDS).pollingEvery(5, SECONDS).ignoring(NoSuchElementException.class);
WebElement dynamicelement = wait.until(new Function<webdriver,webElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("dynamicelement"));
}