Friday, October 26, 2012

Synchronization or Waits in Selenium WebDriver


When our automation execution starts, then there should be fair communication between tool and application.
What i mean here is if the tool is too fast of execution and the application/objects are not fully loaded/not ready by that time, then our automation test cases will fail. So the tool should wait(appropriate) till the objects are present/ready in the application, so that communication/synchronization happens between the tool and application so the chances of our test cases will pass.

Synchronization or Waits can be done in two ways.
1. Explicit Waits
2. Implicit Waits

Explicit Waits:
This can be achieved in 2 ways.

Thread.sleep:
Thread.sleep waits the specified time irrespective of the object state.
Ex: Thread.sleep(30000);
Here the execution is halted for 30 Sec., even if the object you are looking exists in 10 sec. So here tool unnecessarily waits for 20 sec.
Execution wont wait after 30 sec.s even if the object does not available, so the chances of your Test fails.

WebDriverWait:
We can tell the tool to wait only till the Condition met. Once the condition is met, the tool proceed with the next step.
This can be done with WebDriverWait in conjunction with ExpectedConditions Class.
There are few methods supported in ExpectedConditions class to support synchronisation.
Here is the example:
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement o_element = wait.until(ExpectedConditions.elementToBeClickable(By.id("Object Id")));

Here the tool waits a maximum time of 30 Sec., if the object you are looking is displayed in 10 sec. then the execution proceeds with the next step afte 10 secs. rather than waiting for 30 secs.

If you dont want to include any methods in ExpectedConditions class, then you can use below code:
WebDriver driver = new FirefoxDriver();
driver.get("Your URL");
WebElement o_Element = (new WebDriverWait(driver, 30))
  .until(new ExpectedCondition<WebElement>(){
    @Override
    public WebElement apply(WebDriver d) {
        return d.findElement(By.id("Object Id"));
    }});
Here WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully or wait for maximum of 30 sec.


Implicit Waits:
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("Your URL");
WebElement o_Element = driver.findElement(By.id("Object Id"));

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.