Issue
How to use waits in selenium webdriver using c#? I have been asked not to use the foolowing statement by my test manager.
System.Threading.Thread.Sleep(6000);
Solution
It is generally a bad idea to use thread.sleep in UI tests, mostly because what if the web server was just going slower for some reason and it took longer than 6000ms to load that page. Then the test will fail with a false negative. Generally what we use in our tests is the wait for methods in selenium, the documentation can be found at http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp basically the idea is you "wait for" a particular element that you expect to be on the page. By doing this you don't have to manually wait 6000ms when in reality the page took 100ms to load the element that your expecting, so now it only waited for 100ms instead of 6000ms.
Below is some code that we use to wait for an element to appear:
public static void WaitForElementNotPresent(this ISearchContext driver, By locator)
{
driver.TimerLoop(() => driver.FindElement(locator).Displayed, true, "Timeout: Element did not go away at: " + locator);
}
public static void WaitForElementToAppear(this ISearchContext driver, By locator)
{
driver.TimerLoop(() => driver.FindElement(locator).Displayed, false, "Timeout: Element not visible at: " + locator);
}
public static void TimerLoop(this ISearchContext driver, Func<bool> isComplete, bool exceptionCompleteResult, string timeoutMsg)
{
const int timeoutinteger = 10;
for (int second = 0; ; second++)
{
try
{
if (isComplete())
return;
if (second >= timeoutinteger)
throw new TimeoutException(timeoutMsg);
}
catch (Exception ex)
{
if (exceptionCompleteResult)
return;
if (second >= timeoutinteger)
throw new TimeoutException(timeoutMsg, ex);
}
Thread.Sleep(100);
}
}
Answered By - PCG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.