如何在selenium webdriver中使用等待

use*_*912 2 c# selenium

如何使用c#在selenium webdriver中使用等待?我被要求不要使用我的测试经理的愚蠢声明.

System.Threading.Thread.Sleep(6000);
Run Code Online (Sandbox Code Playgroud)

PCG*_*PCG 7

在UI测试中使用thread.sleep通常是一个坏主意,主要是因为如果Web服务器由于某种原因而变慢,并且加载该页面花费的时间超过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);
        }
    }
Run Code Online (Sandbox Code Playgroud)


Lar*_*ars 5

如果您确实需要等待,Task.Delay方法将提供更可预测的结果

Task.Delay(1000).Wait(); // Wait 1 second
Run Code Online (Sandbox Code Playgroud)