How to Use Thread.sleep() in Java With Selenium
Ever wondered how to use Thread.sleep() in Java? This blog explains everything there is to know about Thread.sleep() and how to use it in Selenium Java.
Join the DZone community and get the full member experience.Join For Free
Automating a web application optimizes work flow, helps minimize errors, and makes the product robust. An automated suite will be successful when a system's behavior is predictable. If a system is not predictable, there will be many automation hurdles that need to be handled carefully. Sometimes while automating a web application, we may face an exception,
NoSuchElementException, which is thrown when the element that is being interacted with is not found. This may look weird when you can actually see the element on the webpage, but it has vanished during Selenium test automation.
The principal cause of this exception is that the element we're trying to interact with actually exists on the page but takes time to load and display itself to the user. As you can imagine, this can turn out to be a major issue during automation and can lead our scripts astray. This is where
Thread.sleep() in Selenium Java comes into play. Before we look into the effective use of the
Thread.sleep() Java function, let's take a look at the basics about
Thread.sleep() in Selenium.
What Is Thread.sleep()?
To make our scripts less flaky, we have to add waits which will add some waiting time for an element or all the elements in the webpage to load. The implementation of these waits depends on the type of wait chosen in the automation script. The two most commonly used Selenium Waits are:
Implicit wait: This wait allows you to halt the WebDriver for a specific period of time until the WebDriver is able to locate a desired element on a web page.
Explicit wait: This wait allows you to stop the execution of a script based on a preset condition for a specific amount of time.
However, there are a few instances where
Thread.sleep() would be considered a better choice.
Thread.sleep() is a static Java method that suspends the code for a specific amount of time. It pauses the execution and helps us to know what has happened during this pause. It accepts the time specified in milliseconds. This function is particularly helpful for debugging a website or web page. And this should not be confused with the Selenium waits mentioned above. We will dig deeper into the difference between
Thread.sleep() Java and Selenium waits in the coming sections.
Below is the syntax for
Thread.sleep() in Java:
While using this method, you may face a common exception –
InterruptedException – which has to be handled either by using throws or by a try/catch block as shown below:
Why Do We Use Thread.sleep() in Selenium?
With web applications getting bigger by the minute, it is no surprise that different applications take different amounts of time to load completely.
Thread.sleep() plays a pivotal role in including the page load in our Selenium scripts. Using functions like
Thread.sleep() in Java enables us to run automated tests successfully without causing any script failures. Below are some major reasons why we use
Thread.sleep() in Selenium Java.
Handle Dynamic Elements
There might be times where the application’s webpage has dynamic elements and it will be hard to predict their behavior. For example, most eCommerce websites have a carousel/slider design which changes dynamically. Instead of using Selenium waits to check for the visibility of the web element, we can use
Thread.sleep() to wait for a few seconds.
Reduce Code Complexity
While testing a web page, sometimes the page is loaded but the execution has moved to the next step before we have time to select an option in the webpage. In such cases, we can use either Fluent waits to suspend the time until the element is visible in the page or use
Thread.sleep(). It is better to choose the latter as it involves adding a single line of code rather than adding five to six lines of code in Selenium waits. This implementation avoids unnecessary code complexity.
Instead of making the code complex with the below lines, we can use
Thread.sleep() for some amount of time which reduces the complexity.
Testing Third-Party Systems
While testing the web page(s) which interact with third-party components, we might not know how it was designed. We might not know how long it takes for a web element to be visible on the webpage. Hence, predicting the conditions to handle web elements can seem complex or even impossible. In such situations, we can delay the execution time by using
Thread.sleep()method in Java.
Handle AJAX Calls
Thread.sleep()will be one of the best choices to handle the AJAX calls in the web page as the test will wait for a certain period for the server to respond. There are certain web pages where you can see live scores of a cricket or football match. Here, the score gets updated in specific intervals of time while all the other elements on the webpage remain the same. This is an example of an AJAX call and how handling it with Thread.sleep() is a nice option while executing tests.
Using Thread.Sleep() Java for Selenium Test Automation
Now that you understand why
Thread.sleep() in Selenium Java is a good choice, this section will show you how to implement the function in Selenium test automation. To showcase its implementation, we are using an example of the website easemytrip.com. Here, we will show you an instance of the user selecting the ‘From’ and ‘To’ destination widget, along with a date for their journey.
As expected, easemytrip.com will take some time to load the relevant flight details. To avoid this delay in our script, we will stop thread execution as soon as the user clicks on ‘Search.’ Once we do this, the script will run smoothly, without throwing an exception or error.
Here’s the code snippet:
Let's consider another instance. What if we have another web page on easemytrip.com that takes less or more than the specified amount of time to load? The time spent on locating the element is simply not considered when it comes to
Thread.sleep() in Selenium Java because it is a static wait. Selenium WebDriver will have no choice but to wait for the specified time, regardless of the fact that the element has been located or not. This is why we prefer not to use
Thread.sleep() multiple times in our automation scripts.
Alternatives to Thread.sleep() in Java
People often ask ‘Is it a good practice to use
Thread.sleep()?’ or ‘What can I use instead of
Thread.sleep() has been provided by Java but when used in the automation scripts, it is often considered to be unstable. Ideally, it is not recommended to use
Thread.sleep() in our scripts as it may increase the test execution time (as explained in the last section). Although, while executing tests with third-party interfaces and AJAX calls might seem complex, when handled correctly, with the proper wait like
Thread.sleep(), they will make test execution easier and give highly accurate results.
If that’s not the case with you, you might be better off using other Selenium waits like Implicit Wait, Explicit Wait, or Fluent Wait. You can refer to this tutorial for using Explicit and Fluent Wait in Selenium.
Difference Between Thread.sleep() and Waits
Waits completely cease the execution thread for a specified amount of time. On the other hand,
Thread.sleep()pauses the execution and helps figure out what has happened. But that is not all. Listed below are the key differences between the
Thread.sleep() method and Selenium waits:
sleepis a static method that belongs to the ‘
Thread’ class of Java. On the other hand, Implicit, Explicit, and Fluent Selenium waits are dynamic in nature.
If you use
Thread.sleepwhile performing Selenium test automation, it will stop the execution of the script for the time specified in the script, irrespective of the fact that the element on the web page has been found. Selenium waits do not wait for the complete duration of time. If the WebDriver is able to find the element before the specified time duration, it moves on to the next line of code. This helps in reducing the overall time of script execution by a considerable margin.
Waits are often applied globally, i.e. we only need to write it once in the script and it is applicable for all the web elements specified throughout the WebDriver instance. That is not the case with
Thread.sleep(), where you are required to write it again for each web element. This makes waits a better option than
Thread.sleep()in Selenium Java.
Difference Between Thread.sleep() and Selenium setSpeed()
Now that we know how to use the
Thread.sleep() method in Java, we understand clearly that it is used to delay the code execution.
setSpeed() has a similar role and is also used to delay execution. Yet, the two functions are different from each other.
setSpeed() is basically used to set a specific speed of execution. When running a script in Selenium, there is no delay by default. With the help of
setSpeed(), we can set the length of the delay (in milliseconds) which will then be followed by each execution in that Selenium script.
To put it plainly,
Thread.sleep() makes the WebDriver wait for a specific amount of time before execution and this happens only once. On the other hand,
setSpeed() sets the desired speed of execution or delays execution by a specified amount of time before each operation.
We hope you guys have learned the effective ways of using the
Thread.sleep() method in Java.
Thread.sleep() is a useful method when it comes to web application debugging and can even be implemented with an online Selenium Grid for cross-browser testing platforms.
Let us know if you have come across any other scenarios where you have found a better way to effectively implement this method. Also, if you have any questions, feel free to reach out to us via the comment section below.
Published at DZone with permission of Shalini Baskaran. See the original article here.
Opinions expressed by DZone contributors are their own.