How To Use Thread.sleep() In Java With Selenium?

How To Use Thread.sleep() In Java With Selenium?

Automating a web application optimizes the work, helps minimize errors and makes the product robust. An automated suite would be successful when the behaviour is predictable. If not so, there would be many hurdles in automation 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 to be interacted with actually exists in 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 ashtray. This is where Thread.sleep() in Selenium Java comes into play. Before we look into the effective use of Thread.sleep() Java function, let us understand 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-

  1. 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.
  2. 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 the 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 & Selenium waits in the next sections.

Below is the syntax for Thread.sleep() Java-

//Pauses test execution for specified time in milliseconds
Thread.sleep(1000);

While using this method, you may face a common exception – InterruptedException which has to be handled either by using throws or try catch block as shown below-

try{
Thread.sleep(1000);
}
catch(InterruptedException ie){
}

Or

public static void main(String args[]) throws InterruptedException{
Thread.sleep(1000);
}

In the next sections, we will understand why and how to use Thread.sleep() in Java, first; let’s take a look at why Thread.sleep() Java is used in Selenium test automation.

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 times to load completely. Thread.sleep() plays a pivotal role in including the page load in our Selenium scripts. Using functions like Thread.sleep() Java enables us to run automated tests successfully without coming across any failure of the script. 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 the behaviour. For example, most of the eCommerce websites have carousel/slider design which changes dynamically. Instead of using Selenium waits to check for the visibility of the web element, we can wisely choose Thread.sleep() to wait for a few seconds.

Reduce Code Complexity:

While testing a web page, there is a possibility where the page is loaded, and the execution has moved to the next step, but there wasn’t enough 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 one as it involves adding a single line of code rather than adding five to six lines of code in Selenium waits. This implementation would avoid unnecessary code complexity.

Instead of making the code complex with below lines, we can use Thread.sleep() for some amount of time which reduces the complexity.

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);

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

Testing Third-Party Systems:

While testing the web pages which interact with the 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 in the webpage. Hence predicting the conditions to handle the web elements seems to be complex, sometimes even impossible. In such situations, we can delay the execution time by using Thread.sleep() Java method.

Handle AJAX Calls:

AJAX (Asynchronous JavaScript and XML) is an advanced communication technique where the webpage requests certain information from the server without affecting the current state of the webpage. Thread.sleep() will be one of the best choices to handle the AJAX calls in the web page as the test would 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 in the webpage remain the same. This is an example for AJAX call and how handling it with Thread.sleep() would be one of the better options while executing the tests.

CodingJag

Hey! Are you looking for Zoho Sites Testing ? You can Test your Zoho Sites CSS framework based websites across 3000+ different desktop and mobile browsers

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 user selecting the ‘From’ and ‘To’ destination along with a date of journey.

As expected, easemytrip.com will take some time to load the relevant flight details. To avoid this delay in our script, we will be stopping the thread execution as soon as the user clicks on ‘Search.’ Once we do this, you will see that the script will run smoothly, without throwing an exception or error.

Here’s the code snippet-

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptExecutor;

public class ThreadWait {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        //setting the driver executable
        System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");

        //Initiating your chromedriver
        WebDriver driver=new ChromeDriver();

        driver.manage().window().maximize();


        driver.get("https://www.easemytrip.com/");

        driver.findElement(By.id("FromSector_show")).sendKeys("Delhi", Keys.ENTER);
        driver.findElement(By.id("Editbox13_show")).sendKeys("Mumbai", Keys.ENTER);
        driver.findElement(By.id("ddate")).click();
        driver.findElement(By.id("snd_4_08/08/2019")).click();
        driver.findElement(By.className("src_btn")).click();
        Thread.sleep(5000);
        driver.findElement(By.xpath("//button[text()='Book Now']")).click();    

    }

}

Let us 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.

Hey! Are you looking for Cordova Testing ? You can Test your Cordova CSS framework based websites across 3000+ different desktop and mobile browsers

Alternatives To Thread.sleep() Java

People often ask ‘Is it a good practice to use Thread.sleep()?’ or ‘What can I use instead of Thread.sleep()?’

Well, 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 always seem to be complex which when handled wisely with the proper wait like Thread.sleep() will ease the execution with high accuracy 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() & Waits

Waits completely ceases the execution thread for a specified amount of time. On the other hand, Thread.sleep() pauses the execution and helps us to know what has happened. But that is not all. Listed below are the key differences between Thread.sleep() Java method & Selenium waits-

  • Sleep is a static method that belongs to the ‘Thread’ class of Java. On the other hand, Implicit, Explicit & Fluent Selenium waits are dynamic in nature.
  • If you use Thread.sleep while 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.

Hey! Are you looking for Corona SDK Testing ? You can Test your Corona SDK CSS framework based websites across 3000+ different desktop and mobile browsers

Difference Between Thread.sleep() & Selenium setSpeed()

As we have seen above how to use Thread.sleep() 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 the over execution. Yet, the two functions are different from each other.

Selenium 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 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 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.

Conclusion

We hope you guys have learned the effective ways of using Thread.sleep() Java method by reading this article. Thread.sleep() Java 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 like LambdaTest.

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.

Happy Testing!