我的try catch块中有2个catch,但WebDriverTimeoutException根本没有被捕获。另一个例外是正确捕获。超时异常测试失败" OpenQA.Selenium.WebDriverTimeoutException:20秒后超时"
那么为什么WebDriverTimeoutException try catch根本没被捕获呢?
public IWebElement FindElement(By howBy)
{
TimeSpan _elementTimeOut = TimeSpan.FromSeconds(20);
IWebElement elementfound = null;
WebDriverWait wait = new WebDriverWait(WebDriver, _elementTimeOut);
wait.Until<IWebElement>(d =>
{
try
{
elementfound = WebDriver.FindElement(howBy);
}
catch (WebDriverTimeoutException f)
{
Console.WriteLine("Please fail WebDriverTimeoutException");
}
catch (NoSuchElementException e)
{
Console.WriteLine("Please fail NoSuchElementException");
}
return elementfound;
});
return elementfound;
}
答案 0 :(得分:2)
在WebDriverTimeoutException
块内的匿名方法中未捕获Until()
的原因是匿名方法不会抛出异常。您需要捕获超时外部 Until()
方法。即:
public IWebElement FindElement(IWebDriver driver, By howBy)
{
TimeSpan elementTimeOut = TimeSpan.FromSeconds(20);
IWebElement elementfound = null;
try
{
WebDriverWait wait = new WebDriverWait(driver, elementTimeOut);
elementFound = wait.Until<IWebElement>(d =>
{
try
{
elementfound = driver.FindElement(howBy);
}
catch (NoSuchElementException e)
{
Console.WriteLine("Please fail NoSuchElementException");
}
return elementfound;
});
}
catch (WebDriverTimeoutException)
{
Console.WriteLine("Please fail WebDriverTimeoutException");
}
return elementfound;
}
进一步注意WebDriverWait
已经捕获NoSuchElementException
作为其正常操作的一部分,所以你用你的例子重新发明轮子。执行相同操作的更紧凑和有效的方法如下所示:
public IWebElement FindElement(IWebDriver driver, By howBy)
{
TimeSpan elementTimeOut = TimeSpan.FromSeconds(20);
IWebElement elementfound = null;
try
{
WebDriverWait wait = new WebDriverWait(driver, elementTimeOut);
elementFound = wait.Until<IWebElement>(d => driver.FindElement(howBy));
}
catch (WebDriverTimeoutException)
{
Console.WriteLine("Please fail WebDriverTimeoutException");
}
return elementfound;
}