如何在硒webdriver中使用等待 [英] How to use waits in selenium webdriver

查看:63
本文介绍了如何在硒webdriver中使用等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用C#在Selenium WebDriver中使用等待?测试经理已要求我不要使用以下声明.

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);

推荐答案

在UI测试中使用thread.sleep通常不是一个好主意,主要是因为如果Web服务器由于某种原因运行速度变慢并且花费了更长的时间会怎样?加载该页面的时间超过6000毫秒.然后,测试将失败,并显示假阴性.通常,我们在测试中使用的是硒中的等待方法,可以在 http:中找到该文档.//www.seleniumhq.org/docs/04_webdriver_advanced.jsp 的基本思想是,您等待"您希望在页面上显示的特定元素.这样,您不必手动等待6000毫秒,而实际上页面花费了100毫秒来加载您期望的元素,因此现在它只等待了100毫秒,而不是6000毫秒.

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);
        }
    }

这篇关于如何在硒webdriver中使用等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆