http://www.technicalpage.net/search/label/SQL

Wait in Java

Wait in Java



Wait in Java / Selenium

Two types:
Dynamic Wait
Static Wait

Dynamic Wait:
Page Load timeout
Implicit Wait
Explicit Wait
Fluent Wait

Static Wait:
Thread.sleep();

Page Load Timeout :
This is to test the page load time. if the code takes more than the given time to load the page than the execution fails and we get exception: Timeout Exception
If the page loads before the time limit, it just ignores the remaining time and moves on.

Syntax:
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class HelloWorld {

       public static void main(String[] args) {
             
              WebDriver driver = null ;
              try {
              System.setProperty ("webdriver.chrome.driver","C:\\..path..\\chromedriver.exe" );
              // launch Chrome
              driver = new ChromeDriver();
             
              //Maximize the browser window
              driver.manage().window().maximize() ;
              
              //Wait for the page load for 10 seconds
                          driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

              //Open Google
              driver.get("https://www.google.com" );
                     
              //Find the element(search box) and if found, Enter "Selenium" in the search box.
              driver.findElement(By.xpath("//input[@title='Searchh']")).sendKeys("Selenium");
             
              System.out.println("The Search box is found and the text is entered.");
             
              catch( Exception e) {
                     System.out.println("Pgae did not load in given time limit\n"+e);
              }            
              finally{
                     driver.quit();
              };
       }
}

Implicit Wait :

It waits for a particular element or elements. Once defined, it is applicable to all the elements. That is why, it is also called global wait.  If it finds the element, it moves on and the remaining time is ignored. The beauty of using this wait is , if the element is found/loaded/displayed then it moves to next step, does not unnecessarily spend time waiting until the given time limit.  If it does not find the element with in the given time limit then it shows the error "No Such Element Exception". The default wait time is 0 second.

Syntax:
driver.manage().timeouts().implicitlyWait(TimeOut Limit,TimeUnit.UnitOfTime);
The time unit could be : days, hours, minutes, microseconds, milliseconds, nanoSeconds .
For example, below wait will wait for 10 seconds for the mentioned element , if it finds it enters "Selenium" in the search box and then prints the statement "Search box is found and the text is entered.". It ignores the remaining time once it finds the mentioned element.
If it does not find the  mentioned element, then it wait for maximum of 10 seconds and then it shows exception. In below example, it shows below error message:

Print the error
org.openqa.selenium.NoSuchElementException: with details of the error message.

-------------*-------------
Even after waiting for 10 seconds, The Search box is not found.


To test implicitly wait, you can run a code that tries to find the element which does not exist, the code will fail instantly and shows an error.
Then you can add the implicitly wait of 10 sec and run the code again, the code will fail after 10 seconds.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class HelloWorld {

       public static void main(String[] args) {
             
              WebDriver driver = null ;
              try {
              System.setProperty ("webdriver.chrome.driver","C:\\..path..\\chromedriver.exe" );
              // launch Chrome
              driver = new ChromeDriver();
             
              //Maximize the browser window
              driver.manage().window().maximize() ;
             
              //Open Google
              driver.get("https://www.google.com" );
             
              //Wait for max of 10 seconds if below element is not found
              driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
             
              //Find the element(search box) and if found, Enter "Selenium" in the search box.
              driver.findElement(By.xpath("//input[@title='Searchh']")).sendKeys("Selenium");
             
              System.out.println("The Search box is found and the text is entered.");
             
              } catch( Exception e) {
                     System.out.println("Print the error\n"+e);
                     System.out.println("-------------*-------------");
                     System.out.println("Even after waiting for 10 seconds, The Search box is not found.");
              }            
              finally{
                     driver.quit();
              };
       }

}

Explicit Wait:

In Explicit Wait , the code waits, for the ExpectedConditions to be true ,until the given time limit.
Syntax:
WebDriverWait wait = new WebDriverWait(driver,TimeOutLimit);
WebElement expectedElement = wait.until(ExpectedConditions.presenceOfExpectedElement);
OR
WebElement expectedElement = (new WebDriverWait(driver, TimeOutLimit))
  .until(ExpectedConditions.presenceOfExpectedElement);

Below code will wait for the search box in the google page . If it finds, it prints below result:
OutPut:

The Search box is found now going to enter the text.
The text is entered.

If it does not find the search box on the page , it waits for 10 seconds and then shows an error "Timeout Exception". In our example, it will show below result if it fails:
Output:
Print the error
org.openqa.selenium.TimeoutException: Expected condition failed: waiting for presence of element located by: By.xpath: //input[@title='Searchh'] (tried for 10 second(s) with 500 MILLISECONDS interval)
-------------*-------------
Even after waiting for 10 seconds, The Search box is not found.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class HelloWorld {

       public static void main(String[] args) {
             
              WebDriver driver = null ;
              try {
              System.setProperty ("webdriver.chrome.driver","C:\\..path..\\chromedriver.exe" );
              // launch Chrome
              driver = new ChromeDriver();
             
              //Maximize the browser window
              driver.manage().window().maximize() ;
             
              //Open Google
              driver.get("https://www.google.com" );
             
              //Wait for max of 10 seconds if below element is not found
              WebElement expectedElement = (new WebDriverWait(driver, 10))
                             .until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@title='Search']")));

//OR you can use visibilityOfElementLocated instead of        presenceOfElementLocated like below
//            WebElement expectedElement = (new WebDriverWait(driver, 10))
//                           .until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@title='Search']")));
             
              System.out.println("The Search box is found now going to enter the text.");
             
              //Enter "Selenium" in the search box.
              expectedElement.sendKeys("Selenium");
             
              System.out.println("The text is entered.");
             
              } catch( Exception e) {
                     System.out.println("Print the error\n"+e);
                     System.out.println("-------------*-------------");
                     System.out.println("Even after waiting for 10 seconds, The Search box is not found.");
              }
             
              finally{
                     driver.quit();
              };
       }

}

After "ExpectedConditions." , you can use various methods from the dropdown list as shown below: imageExplicitWait

Fluent Wait:

In Fluent Wait, the code waits until the timeout limit , in the mean time it checks for the expected condition repeatedly in the given time interval(called frequency) until the timeout limit is reached and while waiting and repeatedly checking for the given condition,  we can configure this wait to ignore the given type/s of exception/s.

Below code will open www.google.com and wait for "About" link. If it finds , click that link . If does not finds , waits until 20 secs with repeatedly trying/checking in every 5 seconds. At the same time, it will also ignore "NoSuchElementException" .

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;

import com.google.common.base.Function;

public class fluentWaitTest {

       public static void main(String[] args) throws Exception {

              WebDriver driver = null;
              try {
                     System.setProperty("webdriver.chrome.driver", "C:\\SelPractice\\chromedriver.exe");

                     // launch Chrome
                     driver = new ChromeDriver();

                     // Maximize the browser window
                     driver.manage().window().maximize();

                     // Open Google
                     driver.get("https://www.google.com");

                     //Fluent Wait
                     Wait wait = new FluentWait(driver)                                              
                                  .withTimeout(20, TimeUnit.SECONDS)                    
                                  .pollingEvery(5, TimeUnit.SECONDS)                    
                                  .ignoring(NoSuchElementException.class);  //import org.openqa.selenium.NoSuchElementException;
                     WebElement element = wait.until(new Function(){ //For function() import com.google.common.base.Function;
                    
                           public WebElement apply(WebDriver driver) {
                                 
                                  WebElement expected_Element = driver.findElement(By.xpath("//a[text()='About']"));
                                 
                                  if(expected_Element.isDisplayed()) {
                                  return expected_Element;
                                  } else {
                                         System.out.println("Element not yet displayed.");
                                         return null;
                                  }
                                        
                           }
              });
                     System.out.println("Print Statement after Fluent Wait.");
                     driver.findElement(By.xpath("//a[text()='About']")).click();
                    
                     Thread.sleep(5000);
                    
              }catch (Exception e) {
                     throw e;
              }
             
              driver.close();

       }

}



Static Wait

Thread.sleep(Seconds in milliSeconds);
Thread.sleep(5000);

Above command will make the execution wait for 5 seconds , it does not wait for any element or any condition . It just pause the execution for 5 seconds.





No comments:

Post a Comment