如何在selenium网络驱动程序中使用等待

本文关键字:等待 驱动程序 网络 selenium | 更新日期: 2024-09-23 14:28:53

如何使用c#在selenium webdriver中使用等待?我的测试经理要求我不要使用这种愚蠢的说法。

System.Threading.Thread.Sleep(6000);

如何在selenium网络驱动程序中使用等待

在UI测试中使用thread.sleep通常是个坏主意,主要是因为如果web服务器由于某种原因运行速度变慢,并且加载该页面所需的时间超过6000ms。然后测试将以假阴性结果失败。通常,我们在测试中使用的是硒的等待方法,文档可以在http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp基本上,这个想法是你"等待"一个你期望出现在页面上的特定元素。通过这样做,你不必手动等待6000ms,而实际上页面加载你期望的元素需要100ms,所以现在它只等待100ms,而不是6000ms。

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

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

在需要等待的情况下,Task.Delay方法将提供更可预测的结果

Task.Delay(1000).Wait(); // Wait 1 second

Selenium中也有一个技巧(我使用的是版本4,不确定它是否在早期版本中),但如果您执行了一个操作,并希望等待x个时间,直到该操作完成。例如,当您登录到系统时,可能需要一些时间。

解决方案是:

new WebDriverWait(driver, TimeSpan.FromSeconds(5))
    .Until(d => d.FindElement(By.Id("success_page")).Displayed);