如何使用 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/