Friday, September 30, 2011

Wait For Elements using webdriver

One of the main issues facing automation scripts is using the proper wait for element functions so not to break 
the test and avoid using sleep statements. The WebDriver provides the class WebDriverWait to handle this scenario. The WebDriverWait constuctor can be passed with the required time to wait for each element. It uses the wait() function to handle individual elements which needs to be checked. The wait() function can either check for a boolean condition or a WebElement is actually present.
 
The below example shows the use of WebDriverWait.
 
import com.google.common.base.Function;
import com.google.common.base.Predicate;


Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) { 
  return new Function<WebDriver, WebElement>() { 
    public WebElement apply(WebDriver driver) { 
      return driver.findElement(locator); 
    }
  };
}

Predicate<WebDriver> presenceOfElementLocated1() { 
  return new Predicate<WebDriver>() { 
            public boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().endsWith("demosd");
    }
  };
}

@Test
public void ajxTest() throws InterruptedException{
selenium.open("http://60.240.240.221/web1");
WebDriverWait wait = new WebDriverWait(driver, /*seconds=*/10);
wait.until(presenceOfElementLocated1());
// selenium.click("//input[@type='button']");
  WebElement clickElement = wait.until(presenceOfElementLocated(By.id("anc_5")));
  clickElement.click();
WebElement element = wait.until(presenceOfElementLocated(By.id("anc_4")));
element.click();
Thread.sleep(4000);
}

Note the useage of Predicate and Function above. User needs to import guava.jar
The Predicate interface will return a boolean condition and Function interface converts WebDriver to WebElement.