c# - 如何在 selenium webdriver 中使用等待

标签 c# selenium

如何使用 C# 在 selenium webdriver 中使用等待? 我的测试经理要求我不要使用愚蠢的陈述。

System.Threading.Thread.Sleep(6000);

最佳答案

在 UI 测试中使用 thread.sleep 通常不是一个好主意,主要是因为如果网络服务器由于某种原因变慢并且加载该页面的时间超过 6000 毫秒怎么办。然后测试将失败并出现假阴性。通常我们在测试中使用的是selenium中的等待方法,文档可以在http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp找到。基本上这个想法是您“等待”您希望出现在页面上的特定元素。通过这样做,您不必手动等待 6000 毫秒,而实际上页面需要 100 毫秒来加载您期望的元素,所以现在它只等待 100 毫秒而不是 6000 毫秒。

下面是我们用来等待元素出现的一些代码:

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

关于c# - 如何在 selenium webdriver 中使用等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20549399/

相关文章:

c# - Lambda 表达式和可空类型

c# 替换每一行的最后一个字符

javascript - 类型错误 : Cannot call method 'click' of undefined

javascript - 跟踪页面的每个链接并抓取内容,Scrapy + Selenium

python - 如何使用Python从网页下载所有图像?

c# - 了解 .NET 中的 ConfigurationManager

c# - 从 BSON 序列化为 JSON

c# - WPF DataGrid 移动到最后选定的行而不突出显示最近单击的行

java - 在 Selenium Webdriver 警报上单击“确定”

selenium - WebdriverIO - 截取整页截图