How To Use Thread.sleep() in Selenium – DZone – Uplaza

When performing Selenium automation testing, you would possibly encounter a NoSuchElementException() when the ingredient you are making an attempt to work together with is not discovered.

This error usually happens as a result of ingredient present on the web page however takes a substantial period of time to load and turn into seen to the person. Throughout check automation, this delay might trigger vital points and halt the execution of check scripts. That is the place Thread.sleep() in Selenium could be useful in such circumstances. 

On this weblog, we take a look at easy methods to use Thread.sleep() in Selenium utilizing Java.

What Are Wait Instructions in Selenium?

Earlier than we talk about the Thread.sleep() technique, let’s perceive the wait command in Selenium and its differing kinds. 

Selenium wait instructions are positioned within the check scripts to inform automation to carry on for a sure period of time or till a selected situation is met earlier than continuing with the subsequent step. This prevents errors from occurring if parts on the net web page aren’t absolutely loaded or interactive but. 

Listed below are the various kinds of wait instructions in Selenium:

Implicit Waits

These waits are used to seek for a WebElement if it wants a while to load and isn’t instantly out there. The implicit waits are globally utilized to all of the WebElements on the net web page and stay within the WebDriver object. It’s non-blocking and doesn’t look forward to all the period, like Thread.sleep().

If the WebElement isn’t discovered through the specified time, it is going to throw the NoSuchElementException()

Instance:

driver.handle().timeouts().implicitlyWait(Length.ofSeconds(10));

Specific Waits

These waits are used to attend for a specified time till the anticipated situation is met. This anticipated situation could be set utilizing the category ExpectedConditions in Selenium. Specific waits could be utilized to a selected WebElement and don’t have an effect on the opposite WebElements on the net web page. It can throw the TimeOutException if the WebElement isn’t discovered throughout the specified time.

Instance:

WebDriverWait wait = new WebDriverWait(driver, Length.ofSeconds(5));
WebElement checkoutBtn = driver().findElement(By.cssSelector("#check"));
wait.till(ExpectedConditions.visibilityOf(checkoutBtn));

Within the instance code above, the checkout button is positioned utilizing the express wait. The WebDriverWait class is instantiated during which the WebDriver occasion and the time period are offered. Utilizing the ExpectedConditions class, the situation is ready to attend till the checkout button is seen.

Fluent Waits

These waits are extra superior and versatile than implicit and express waits. They permit the person to outline a customized situation and the polling interval. It additionally gives an choice to ignore the desired exceptions through the time period whereas ready for the WebElement. This helps in ready for the WebElements that will change over time.

Instance:

public String successMessageText() {
Wait wait = new FluentWait(driver)
.withTimeout(Length.ofSeconds(10))
.pollingEvery(Length.ofSeconds(2))
.ignoring(NoSuchElementException.class);
 
WebElement successMessage = wait.till(driver -> notificationPopUp().findElement(By.tagName("p")));
return successMessage.getText();

Within the above code instance, the successMessageText() technique returns a textual content from a WebElement utilizing fluent wait. The Wait interface is used to instantiate the fluent wait of 10 seconds that shall be polling at a frequency of each 2 seconds, ignoring NoSuchElementException(). Lastly, it is going to return the textual content in String format.

What Is Thread.sleep() in Selenium?

To make the automated check scripts much less flaky, there’s a want so as to add waits, which is able to add some ready time for a component or all the weather within the internet web page to load. Implementing these waits will depend on the kind of wait within the automation script.

The 2 mostly used Selenium waits are implicit and express. Nonetheless, there are a number of situations the place Thread.sleep() in Selenium can be thought-about a better option. Thread.sleep() is a static Java technique that suspends the code for a selected time. It pauses the execution and helps us to know what has occurred through the pause. It accepts the time laid out in milliseconds. This perform is especially useful for debugging a web site or internet web page. 

Syntax for Thread.sleep() in Selenium

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

Whereas utilizing this technique, you could face a standard exception – InterruptedException, which needs to be dealt with both by utilizing throws or try-catch blocks as proven beneath:

strive{
Thread.sleep(1000);
}
catch(InterruptedException ie){
}
Or
public static void fundamental(String args[]) throws InterruptedException{
Thread.sleep(1000);
}

Within the subsequent sections, we’ll perceive why and easy methods to use Thread.sleep() in Selenium. Let’s first check out why the Thread.sleep() technique is used for Selenium automation.

Why Use Thread.sleep() in Selenium?

As internet functions proceed to develop in complexity, their loading instances differ tremendously. The Thread.sleep() technique turns into important in accounting for these various load instances inside our Selenium scripts. Utilizing Thread.sleep() in Selenium ensures clean execution of automated exams, stopping script failures. 

Listed below are some key explanation why Thread.sleep() technique is utilized in Selenium:

Deal with Dynamic Parts

There could be instances when the net web page has dynamic parts, and will probably be arduous to foretell the conduct. For instance, most E-commerce web sites have a carousel/slider design that adjustments dynamically. As an alternative of utilizing Selenium waits to verify for the visibility of the net ingredient, we will select the Thread.sleep() technique to attend for a number of seconds.

Debugging

The Thread.sleep() technique helps debug the net automation check failures. For instance, the exams failing as a result of NoSuchElementException() could be debugged by including a Thread.sleep() technique, permitting the code to attend for two to five seconds.

This may assist in higher visibility of the failure to know if the check fails because the ingredient couldn’t be loaded through the code execution. After including the Thread.sleep() technique, if the check passes, then it must be famous that we will add express or fluent waits within the check to attend for the WebElement to be loaded earlier than the check strikes to the subsequent line to work together with the WebElement.

Testing Third-Get together Parts

When testing internet pages that work together with third-party elements, it is very important perceive how they have been designed as an alternative of realizing how lengthy it takes for a WebElement to be seen on the net web page. Therefore, predicting the situations to deal with the WebElements appears complicated and generally even unattainable. In such conditions, we will delay the execution time utilizing the Thread.sleep() technique.

Deal with AJAX Calls

Asynchronous JavaScript and XML (AJAX) are superior communication strategies that permit the net web page to request particular info from the server with out affecting the present state of the net web page. The Thread.sleep() technique shall be among the best selections to deal with the AJAX calls on the net web page, because the check would wait a sure interval for the server to reply.

Distinction Between Selenium Waits and Thread.sleep()

On this part, we’ll dig deeper into the distinction between Selenium waits and the Thread.sleep() technique.

Side Selenium Waits (Implicit, Specific, Fluent) Thread.sleep()
Belongs to Selenium framework Thread class of Java
Execution Suspension Waits till a specified situation is met or a timeout happens Ceases execution thread for a specified time
Script Execution Strikes to the subsequent line if the ingredient is discovered earlier than the desired time Pauses script execution, no matter ingredient presence
Applicability Applies globally; it must be written as soon as for all the WebDriver occasion. Must be written for every internet ingredient
Affect on Script Execution Time Helps scale back script execution time Will increase script execution time
Most popular Possibility in Selenium Java Most popular resulting from environment friendly dealing with of ingredient wait situations Much less most popular resulting from its blocking nature

Demo: Utilizing Thread.sleep() in Selenium for Take a look at Automation

On this part, let’s dive into the demonstration and verify easy methods to implement the Thread.sleep() in Selenium Java. 

To showcase its implementation, we’ll use an instance of the LambdaTest eCommerce Playground web site. The exams shall be executed on a cloud-based testing platform like LambdaTest utilizing Chrome browser on Home windows 10. 

Take a look at State of affairs

  1. Navigate to the Account Login web page.
  2. Enter the legitimate particulars within the E-Mail Deal with and Password fields and click on the Login button.
  3. After profitable login, look forward to the subsequent web page to load utilizing the Thread.sleep() technique and confirm the web page header reveals the textual content My Account on the web page.

Login Web page – LambdaTest eCommerce Playground Web site

My Account Web page – LambdaTest eCommerce Playground Web site

Take a look at Implementation

Let’s first create a brand new Java class file named ThreadSleepDemoTests.java. This class may have all implementations of the check situation in addition to the configuration required for operating the exams on the LambdaTest Cloud Grid.

public class ThreadSleepDemoTests {

   personal WebDriver driver;
   // …

}

The setup() technique is created contained in the ThreadSleepDemoTests class, which has the configuration particulars to run the check on the LambdaTest on-line Selenium Grid.

@BeforeTest
public void setup() {
   last String userName = System.getenv("LT_USERNAME") == null ? "LT_USERNAME" : System.getenv("LT_USERNAME");
   last String accessKey = System.getenv("LT_ACCESS_KEY") == null ? "LT_ACCESS_KEY" : System.getenv("LT_ACCESS_KEY");
   last String gridUrl = "@hub.lambdatest.com/wd/hub";
   strive {
       this.driver = new RemoteWebDriver(new URL("http://" + userName + ":" + accessKey + gridUrl), getChromeOptions());
   } catch (last MalformedURLException e) {
       System.out.println("Could not start the remote session on LambdaTest cloud grid");
   }
}

LambdaTest Username and Entry Key values are necessary values with out which the exams can’t be run on the LambdaTest cloud platform. As these are confidential values, they shouldn’t be hardcoded within the code. We’ll cross these values utilizing surroundings variables. 

Some extra capabilities associated to the LambdaTest platform, equivalent to browser identify, browser model, check identify, construct identify, and many others., have to be handed to run the exams on the LambdaTest Cloud Grid. These capabilities can simply be set utilizing the LambdaTest Automation Capabilities Generator.  The configuration values shall be handed by creating a brand new technique getChromeOptions() within the ThreadSleepDemoTests class:

public ChromeOptions getChromeOptions() {
   last var browserOptions = new ChromeOptions();
   browserOptions.setPlatformName("Windows 10");
   browserOptions.setBrowserVersion("123.0");
   last HashMap ltOptions = new HashMap();
   ltOptions.put("project", "Thread.sleep Demo on Cloud");
   ltOptions.put("build", "LambdaTest e-commerce website test");
   ltOptions.put("name", "Thread.sleep demo test");
   ltOptions.put("w3c", true);
   ltOptions.put("plugin", "java-testNG");

   browserOptions.setCapability("LT:Options", ltOptions);

   return browserOptions;

}

As talked about earlier, we shall be operating the exams on the Chrome browser on a Home windows 10 machine. These respective capabilities are offered within the above technique. 

The next @Take a look at technique will implement the check situation we mentioned earlier for the demo:

@Take a look at
public void testLogin() throws InterruptedException {
   this.driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=account/login");

   last WebElement emailAddress = this.driver.findElement(By.id("input-email"));
   emailAddress.sendKeys("david.thomson@gmail.com");

   last WebElement password = this.driver.findElement(By.id("input-password"));
   password.sendKeys("Secret@123");

   last WebElement loginBtn = this.driver.findElement(By.cssSelector("input.btn-primary"));
   loginBtn.click on();

   Thread.sleep(3000);

   last String myAccountHeaderText = driver.findElement(By.cssSelector("#content h2")).getText();
   assertEquals(myAccountHeaderText, "My Account");
}

The check script will first navigate to the Account Login web page of the LambdaTest E-commerce Playground web site. It can seek for the E-Mail Deal with subject and sort within the worth david.thomson@gmail.com in it. 

Subsequent, the Password subject shall be positioned, and the worth Secret@123 shall be typed in. Lastly, it is going to find the Login button, and click on on it. 

After the Login button is clicked, the web site will navigate to the My Account web page, which is able to take a while to load. Therefore, the Thread.sleep() technique is used right here to attend for 3000 milliseconds earlier than it checks the web page header of the My Account web page. 

Utilizing the Thread.sleep() technique right here, the My Account web page is loaded efficiently, after which the assertion is carried out. 

Take a look at Execution 

Following is the screenshot of the check execution carried out utilizing IntelliJ IDE: 

The check execution particulars could be discovered on the LambdaTest Net Automation Dashboard. 

You may view the small print of check execution for the exams executed on the Chrome 123 model of the Home windows 10 platform, which took 10 seconds to run the check. 

Particulars equivalent to logs, video recordings, and many others., could be considered on the Net Automation Dashboard. 

How To Keep away from A number of Thread.sleep() in Selenium

Whereas working with some web sites which have gradual response instances and take time to load, it’s noticed that testers use a number of Thread.sleep() strategies within the check in order that WebElements could be loaded efficiently on the net web page earlier than the code tries to find the WebElement on the web page. 

Think about the next code instance of LambdaTest E-commerce Playground web site the place the person navigates to the House web page, waits for it to load earlier than clicking on the Store by Class menu, after which clicks on the MP3 Gamers class and once more waits for the subsequent web page to load. 

House Web page – LambdaTest eCommerce Playground Web site

Store by Class menu  

Right here is the check script with a number of Thread.sleep() strategies:

@Take a look at
public void testWebsiteNavigation () throws InterruptedException{
   this.driver.get("https://ecommerce-playground.lambdatest.io/");
   Thread.sleep(1000);

   this.driver.findElement(By.linkText("Shop by Category")).click on();

   Thread.sleep(1000);

   this.driver.findElement(By.cssSelector(".entry-component .entry-widget nav.navbar ul li:nth-child(5) a")).click on();

   Thread.sleep(1000);

}

Take a look at Execution

When this code was executed, it took a complete of 14 seconds to run. It additionally took 3000 milliseconds or 3 seconds, contemplating the Thread.sleep() technique has 1 second arduous wait after each line of code. 

Therefore, utilizing a number of Thread.sleep() strategies within the exams isn’t a beneficial strategy. As an alternative, express waits from Selenium could possibly be used right here as it’s dynamic in nature and can transfer to the subsequent line of code as soon as the WebElement is discovered, saving the time of execution.

Utilizing Specific Wait As an alternative of Thread.sleep()

The next code could possibly be used, which makes use of express wait, and may carry out sooner execution as in comparison with the code utilizing the Thread.sleep() technique. 

Right here is the check script with express wait as an alternative of Thread.sleep() technique:

@Take a look at
public void testWebsiteNavigationWithExplicitWait() {
   this.driver.get("https://ecommerce-playground.lambdatest.io/");

   last WebDriverWait wait = new WebDriverWait(this.driver, Length.ofSeconds(10));

   wait.till(ExpectedConditions.elementToBeClickable(By.linkText("Shop by Category"))).click on();

   wait.till(ExpectedConditions.elementToBeClickable(By.cssSelector(".entry-component .entry-widget nav.navbar ul li:nth-child(5) a"))).click on();
}

Take a look at Execution

When this code was executed, it took a complete of 11 seconds to finish the execution. Thus, it saves the three seconds that have been moreover taken within the earlier check execution, which was carried out utilizing the Thread.sleep() technique. Therefore, it’s endorsed to make use of Selenium waits within the exams moderately than the Thread.sleep() technique.

Aspect Is Discovered Utilizing Thread.sleep() however Not Implicit/Specific Waits

You would possibly come throughout some eventualities the place the WebElement could possibly be positioned utilizing the Thread.sleep() technique solely. While you attempt to use the Selenium waits as an alternative of the Thread.sleep() technique, the WebElements usually are not positioned, ensuing within the failure of the exams. 

In such circumstances, it’s endorsed to debug the check and verify for the precise reason for the error that ends in the failure of the exams. Right here, the Thread.sleep() technique could possibly be used as a debugging mechanism to diagnose the check failure. 

For instance, an overlay seems on the web page when the person tries to click on on a button, which ends up in ElementClickInterceptionException and results in check failures. Alternate methods must be seemed out for to deal with the failure as an alternative of straight utilizing the Thread.sleep() technique.

There are a number of issues that may be checked, like selectors being right, utilizing applicable locator technique, checking if the net web page masses appropriately, and solely the required interplay being carried out on the WebElement

One other different is to look out for the basis reason for the check failure to know why the implicit or express wait isn’t working to find the ingredient. For instance, finding the overlay web page, clicking on it, after which interacting with the specified WebElement on the web page. 

Equally, the pause() technique can be utilized from the Actions class in Selenium. The pause() technique will pause the execution of the exams for the desired period.

Limitations of Utilizing Thread.sleep() in Selenium

Although the Thread.sleep() technique helps deal with dynamic WebElements, debugging, and testing third-party elements, it has limitations. 

The next are a number of the limitations of the Thread.sleep() in Selenium:

Static Exhausting Coded Waits

The thread.sleep() technique doesn’t adapt to the precise state of the appliance underneath check. It can halt the check execution for the desired period of time no matter if the WebElement is discovered throughout the specified time or not. In case of any error or check failures, it is going to occur after the desired period of time.

Unreliable

It isn’t dependable as it would get interrupted resulting from different threads or processes and could possibly be affected by elements equivalent to community points.

Not Scalable

It will increase the general check execution time, which can lead to delayed builds for testing. This will additionally result in delays in getting suggestions on the builds.

Alternate options to Thread.sleep() in Selenium

The thread.sleep() technique has been offered by Java, however when utilized in automation scripts, it’s usually thought-about unstable. Ideally, it isn’t beneficial to make use of the Thread.sleep() technique in check scripts as it could enhance the check execution time (as defined within the final part). 

Though executing exams with third-party interfaces and AJAX calls would possibly at all times appear complicated, when dealt with correctly with the correct wait just like the Thread.sleep() technique, it is going to ease the execution with high-accuracy outcomes. 

If that’s not the case with you, you could be higher off utilizing different Selenium waits like implicit, express, or fluent waits.

SmartWait Performance

Cloud-based testing platforms like LambdaTest provide SmartWait performance for Selenium testing that permits you to do away with the undesirable express waits and anticipated situations within the code. It ensures that the actions are carried out on the WebElements, that are prepared for interplay.

If the actionability checks fail, it throws the related Selenium exceptions, which helps shortly determine and resolve the check automation-related points.

SmartWait helps in writing optimized code that’s straightforward to learn and keep. As soon as the SmartWait functionality is used within the code, there isn’t any want to make use of express, implicit, or fluent waits within the check scripts. 

The smartWait functionality could be added to the LT:Choices functionality, which permits the addition of all of the capabilities associated to the LambdaTest Cloud Grid.

LT:Choices {
...

"smartWait": 10 // It accepts integer values as second

...
}

The time in seconds must be handed within the smartWait functionality. This functionality accepts solely integers. We’ll cowl the demonstration of smartWait within the check script within the subsequent part of this weblog.

SmartWait for Selenium Take a look at Automation

Within the earlier part, we discovered easy methods to use the Thread.sleep() technique in Selenium automation. A number of Thread.sleep() strategies have been required to be added to the check scripts to make the execution wait whereas the display transition occurred. These Thread.sleep() strategies helped clean the execution of the exams, avoiding the flaky exams. 

Nonetheless, because the Thread.sleep() technique is a tough wait, the check execution time elevated by an extra 3000 milliseconds. The SmartWait characteristic by LambdaTest may also help us scale back the check execution time by eliminating the usage of the Thread.sleep() technique. 

Let’s take the identical login situation of the LambdaTest E-Commerce Playground web site.

 The next smartWait functionality shall be added to the getChromeOptions() technique.

public ChromeOptions getChromeOptions() {
//...
ltOptions.put("smartWait", 20);

//...

}

The next screenshot reveals the implementation of the getChromeOptions() technique.  

The testLoginWithSmartWait() technique performs the identical login situation steps as mentioned earlier. Nonetheless, on this check technique, there isn’t any Thread.sleep() technique used to attend for the My Account display to load after the login button is clicked. 

LambdaTest SmartWait internally handles all of the WebElement readiness for performing actions. This protects the check execution time with out writing any further boilerplate code. 

In line with the Way forward for High quality Assurance Survey by LambdaTest, testers spend greater than 8% of their time fixing flaky exams. Nonetheless, the SmartWait performance allows testers to deal with performing core testing with out worrying about check flakiness, saving them beneficial time to write down environment friendly check scripts.

@Take a look at
public void testLoginWithSmartWait() {
   this.driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=account/login");

   last WebElement emailAddress = this.driver.findElement(By.id("input-email"));
   emailAddress.sendKeys("david.thomson@gmail.com");

   last WebElement password = this.driver.findElement(By.id("input-password"));
   password.sendKeys("Secret@123");

   last WebElement loginBtn = this.driver.findElement(By.cssSelector("input.btn-primary"));
   loginBtn.click on();

   last String myAccountHeaderText = this.driver.findElement(By.cssSelector("#content h2")).getText();
   assertEquals(myAccountHeaderText, "My Account");
}

Take a look at Execution

Let’s execute the testLoginWithSmartWait() technique and likewise the beforehand written check testLogin() that has the Thread.sleep() technique applied that we mentioned within the earlier part of this weblog, and evaluate the check execution time taken by each of the exams. 

This complete time of execution could be verified on the LambdaTest construct particulars display, as proven within the screenshot beneath:  It may be noticed that the check with the Thread.sleep() technique took a complete of 8 seconds to run. Nonetheless, the check with LambdaTest SmartWait took solely 6 seconds to run. Thus, saving 2 seconds in the entire check execution.

It is a easy login situation, so the time distinction is far much less. Nonetheless, it may be imagined that in complicated eventualities equivalent to end-to-end testing, this execution time can play an important position. 

Conclusion

Thread.sleep() in Selenium is a sort of arduous wait that can be utilized in Selenium internet automated exams. 

Nonetheless, it isn’t a beneficial apply. As an alternative, we must always implement the Selenium waits, which is a extra versatile and fewer time-consuming answer. Thread.sleep() in Selenium is a helpful technique for internet utility debugging and may even be applied with a web-based Selenium Grid. 

Tell us you probably have come throughout another eventualities the place you could have discovered a greater technique to successfully implement the Thread.sleep() technique utilizing Selenium with Java. Additionally, you probably have any questions, be at liberty to succeed in out by way of the remark part beneath.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version