Wednesday, 27 May 2015

Thread.Sleep really required in Selenium Automation?

I have seen many automation engineers using fixed wait (sleep) statements in selenium or any other automation tool. My personal opinion says that we should never use fixed wait statements in the code as it will slow down the test execution unnecessarily. Sometimes fixed sleep statements might solve your problems. Let us say you added a statement to wait for 5 seconds and the code is working fine today but what will happen if in next release 5 second wait is not sufficient. We never know. This is a risky approach and a bad coding practice.

When the test cases are failing due to synchronization issues, we often tend to blame the network speed, application latency or browser limitations. But that is not the case at all times. You can avoid these wait statements in your code by adopting standard coding practices as mentioned below.

  1. Use WebDriverWait and ExpectedConditions class - I recommend that we should use these classes whenever we think that test might fail due to synchronization issue. With the help of these classes we can make selenium webdriver wait until some condition is satisfied like specific element getting enabled or displayed.
  2. While switching to the new browser window, ensure that the web document is really loaded into the window before trying to perform any operation. In one of the projects, I faced the issue in which I was trying to switch to the window. But due to the latency, test was failing unpredictably. I ensured that count of window handles is 2. But still I was facing the issue in random runs. I used 10 second fix wait but still problem persisted. I kept on increasing the sleep time but finally I realized that there must be better technique to handle this scenario. Then I used a loop to check that title of the window has changed  as per the expected one and then I tried to switch to it. This made my code more robust. This is how I got rid of sleep statements in the code. If you are still not able to switch to the new window, try to switch to the first window and re-switch to the new window. 
  3. Another scenario where testers often use wait statements is when selecting the value from the drop down. The issue here is - After selecting the value from the drop down box, new web controls or elements are added or removed from the page dynamically. In this situation, sometimes page itself become unresponsive. In this case, we can use custom function which will use loop until we have performed our operation successfully.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

About Me

My photo

Self-motivated software professional