Saturday, October 13, 2012

Implicit wait Vs. Explicit wait

WebDriver Waits
Implicit wait

WebDriver driver = new FirefoxDriver();  
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. So in this case, you are telling WebDriver that it should wait 10 seconds in cases of specified element not available on the UI (DOM).


  • Implicit wait time is applied to all elements in your script



Explicit wait (By Using FluentWait)

public static WebElement explicitWait(WebDriver driver,By by)  
{  
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)  
             .withTimeout(20, TimeUnit.SECONDS)  
             .pollingEvery(2, TimeUnit.SECONDS)  
             .ignoring(NoSuchElementException.class); 

     WebElement element= wait.until(new Function<WebDriver, WebElement>() {  
           public WebElement apply(WebDriver driver) {  
             return driver.findElement(By.id("foo"));  
            }  
      });  
  return 


Explicit waits are intelligent waits that are confined to a particular web element. Using explicit waits you are basically telling  WebDriver at the max it is to wait for X units of time before it gives up.

  •  In Explicit you can configure, how frequently (instead of 2 seconds) you want to check condition
  • Explicit wait time is applied only for particular specified element.
Explicit wait

public static WebElement explicitWait(WebDriver driver,By by)  
 {  
      WebDriverWait wait = new WebDriverWait(driver, 30);  
      wait.until(ExpectedConditions.presenceOfElementLocated(by));  
 }       

In above method it will wait until either ExpectedConditions become true or Timeout (30 sec).

2 comments:

  1. So doesn't this mean that explicit waits are better as it will come out as soon as the element is found while in implicit if set to 10 s and element has appeared after 5s, even then it will wait for 5sec

    ReplyDelete
    Replies
    1. No. Implicit wait also will come out once the element found but, it will be useful only when entire page loads. (i.e., It won't wait for dynamically loading ajax elements) .

      Delete

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