Implicit vs Explicit vs Fluent And Sleep in Selenium
Why Do We Need Selenium Waits when there is Sleep in java ?
Most of the time a common problem faced by almost all automation tester is "ElementNotVisibleException". I saw the people scratching their head because of this!. Visually, when seeing the UI execution of script, we face a common question that, "we can see the element but why our script cant find this!!"❓ here is the catch!
Usually, when navigation happens from one page to other/ on dynamically loading or hiding elements, there will be a delay of fractions. Hence, some time our eye won't catch that, though script may encounter of fail to find element. Hence, to resolve this we should apply wait!
Types of Selenium Waits For Page Load
- Thread.Sleep() method
- Implicit Wait
- Explicit Wait
- Fluent Wait
Thread.Sleep() For Automation Testing with Selenium
Sleep is a static method that belongs to the thread class in java. This method can be called using the reference of the class name i.e Thread. If you use Thread.sleep while performing automation testing with Selenium, then this method will stop the execution of the script for the specified duration of time, irrespective of whether the element is found or not on the web page.
It accepts the time duration in milliseconds.
The syntax for the same is:
Thread.sleep(3000);
The sleep function throws InterruptedException so it should be handled using a try-catch block as below:
try{
Thread.sleep(5000);
}
catch(InterruptedException ie){
}
***This is not recommended in selenium as it introduce unwanted delays even element is loaded before timeout!
Also, sometime it may take more time to load few pages base on various criteria like internet speed, machine speed etc, in this case, script will wait dumb for given time and try to locate the element and result in failure.
Implicit Wait For Automation Testing with Selenium
Selenium has overcome the problems provided by Thread.sleep() and have come up with two Selenium waits for page load. One of which is Implicit wait which allows you to halt the WebDriver for a particular period of time until the WebDriver locates a desired element on the web page.
The key point to note here is, unlike Thread.sleep(), it does not wait for the complete duration of time. In case it finds the element before the duration specified, it moves on to the next line of code execution, thereby reducing the time of script execution. This is why Implicit wait is also referred to as dynamic wait. If it does not find the element in the specified duration, it throws ElementNotVisibleException.
Another interesting thing to note about Implicit wait is that it is applied globally, which makes it a better option than Thread.sleep(). Meaning you only need to write it one time and it gets applicable for all of the web elements specified on a script throughout the WebDriver instance. Convenient isn’t it? The syntax to achieve the same is:
driver.manage().timeouts().implicitlyWait(Time Interval to wait for, TimeUnit.SECONDS);
The default time for Implicit wait is zero and it keeps polling for the required element after every 500 milliseconds. Let’s see the code snippet below, showcasing the use of Implicit wait.
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Now, here we are aware of the fact, that pages shall we loaded in a certain duration, but what if we do not know the element to be visible/clickable at loading time. As in the time of its appearance is dynamic and keeps on changing from time to time. In this case, Explicit wait will help you overcome this problem. Let’s investigate its detail.
Explicit Wait For Automation Testing with Selenium
The Explicit wait is another one of the dynamic Selenium waits. Explicit wait help to stop the execution of the script based on a certain condition for a specified amount of time. Once the time goes overboard, you will get the ElementNotVisibleException. In a scenario where you do not know the amount of time to wait for, this explicit wait comes in handy. Using conditions like elementToBeClickable() or textToBePresentInElement(), one can wait for the specified duration. One can use these predefined methods using the combination of classes WebDriverWait and ExpectedConditions. In order to use this case, import the below packages in your class:
import org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.support.ui.WebDriverWait
Post this one needs to create a reference variable for the WebDriverWait class and instantiate it using the WebDriver instance and providing the amount of Selenium wait for page load, one may need. The unit of time is in seconds. One can define it as below:
WebDriverWait wait = new WebDriverWait(driver,30);
In order to use the predefined methods of the ExpectedCondition Class, we will use the wait reference variable as below:
wait.until(ExpectedConditions.visibilityOfElementLocated(Reference of Element ID to be located using locator));
Types of Expected Conditions:
Below are the few types of expected conditions commonly used as you perform automation testing with Selenium.
- visibilityOfElementLocated()- Verifies if the given element is present or not
- alertIsPresent()- Verifies if the alert is present or not.
- elementToBeClickable()- Verifies if the given element is present/clickable on the screen
- textToBePresentInElement()- Verifies the given element have the required text or not
- titlels()- Verify the condition wait for a page that has a given title
** When implicit wait and explicit wait are given in conjunction, then they work on cumulative time, rather than on a single wait condition. For example, if the Implicit wait is given for 30 seconds and the Explicit wait is given for 10 seconds, then the explicit element it is looking for will wait for 40 seconds.
Fluent Wait For Automation Testing with Selenium
The Fluent wait is similar to explicit wait in terms of its functioning. In Fluent wait, you perform a Selenium wait for an element when you are not aware of the time it may take to be visible or clickable. The few differential factors that Fluent wait offers are:
- The polling frequency- In case of Explicit wait, this polling frequency is by default 500 milliseconds. Using Fluent wait, you can change this polling frequency based on your needs, i.e you can tell your script to keep checking on an element after every ‘x’ seconds.
- Ignore Exception- During polling, in case you do not find an element, you can ignore any exception like ‘NoSuchElement’ exception etc.
Apart from these differential factors, like Explicit wait or Implicit wait, you can define the amount of time to wait for the element to be visible or actionable. The below syntax or lines of code are used to define Fluent wait in Selenium:
Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
.withTimeout(60, SECONDS) // this defines the total amount of time to wait for
.pollingEvery(2, SECONDS) // this defines the polling frequency
.ignoring(NoSuchElementException.class); // this defines the exception to ignore
WebElement foo = fluentWait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) //in this method defined your own subjected conditions for which we need to wait for
{ return driver.findElement(By.id("foo"));
}});
Conclusion:
Even though the fluent wait looks complex, it is the best and popular method used when writing selenium framework for larger functionalities. Based, on feature complexity and execution time, we should select the appropriate waits which suites best!
Comments
Post a Comment