Beyond for the purpose of temporarily intentionally delaying Selenium at designated points for debugging, is there ever a valid purpose for a Thread.sleep(x) in a run?

This could apply to any language, using the corresponding Thread Sleep functions.

  • 1
    Thread.sleep is a crude but effective tool in any automation suite. I would always try to avoid using it, as it introduces an inflexible delay that may not be required. If possible (regardless of automation solution) have a check to see if the next testable object is available before progressing, rather than just waiting for 2/5/10 seconds. It's a technically better solution. That said, I do use sleep commands when I'm looking to automate something quickly. I do feel guilty about it and try to remove them before my scripts are reviewed. :) – Dave M Apr 14 '16 at 11:41
  • I agree Dave. I do use them when building out a quick crude utility to 'just do something' and more than I'd like to admit when debugging. – Paul Muir Apr 14 '16 at 12:08

In a word, yes.

Here's one scenario where it was necessary to sleep for a specified number of seconds:

The application could display credit card numbers to a small number of users who had the privilege to view secured data. The display window was designed to log who viewed the data and which transaction was being viewed; and to close itself after a configurable length of time.

My scripts would set the display time to a short enough value that the delay wasn't excessive, then open the secured data. At this point the script would sleep for the length of the display time, then check that the form no longer displayed.

With the tool I was using at the time, this was the simplest and cleanest way to verify that the display time was being honored.

  • Agreed, but it matters how you script it. I prefer to explicitly say, what you're waiting for, e.g., waitThat(secureNumberIsNoLongerShown, noLonger(seconds(30))). – dzieciou Apr 14 '16 at 12:13
  • @dzieciou - as I said, in the tool I was using at that time, the method I chose was the cleanest way to verify the timeout. – Kate Paulk Apr 15 '16 at 11:41

I/O APIs often incorporate timeout values. The purported best way to test time-related code is to take control of the clock, but sometimes that is not practical, e.g. because you use a third-party, time-dependent library that you do not want to modify. In those cases, the best way to test what happens after a timeout is to sleep for the timeout period.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.