Sleeps and Pauses

Problem
Your test automation isn’t synchronizing well with the application under test (AUT). You need a way for your script to wait until the application is ready for the next action. Should you implement sleeps or pauses in your tests to overcome the problem? Thread.Sleep(), anyone?

Solution
As a general rule, you should not insert pauses or sleeps into your automation code. The best solution is to write a custom routine or leverage an existing library (e.g. Selenium WebDriver) to wait on a property of a UI element.

Comments
Sprinkling hard-coded sleeps in automation code isn’t desirable, because scripts will wait for a specified amount of time regardless of the application’s speed. And, as a result, they will take longer to execute.

Example

// Wrong. Note the sleep that waits 5 seconds for the page to refresh.
browser.FindElement(By.Id("submitButton")).Click();
System.Threading.Thread.Sleep(5000);
Assert.That(browser.FindElement(By.TagName("body")).Text.Contains("Order No:"));

// Correct. Explicitly wait for an element before proceeding.
browser.FindElement(By.Id("submitButton")).Click();
WebDriverWait wait = new WebDriverWait(browser, TimeSpan.FromSeconds(5));
wait.Until(brw => brw.FindElement(By.Id("orderNo")));
Assert.That(browser.FindElement(By.TagName("body")).Text.Contains("Order No:"));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s