2016-12-24 118 views
0

我在我的try catch块中有2个抓取,但WebDriverTimeoutException根本没有被捕获。另一个例外被正确捕获。超时例外测试失败“OpenQA.Selenium.WebDriverTimeoutException:20秒后超时”尝试抓取WebDriverTimeoutException不起作用

那么为什么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; 
    } 

回答

1

的原因,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; 
} 
+0

非常感谢你JimEvans,你的建议真的有效。现在我的方法看起来更小,效率更高。 – Patrick