Selenium Webdriver:处理NoSuchElementException的最佳实践

时间:2014-04-01 08:50:24

标签: java selenium-webdriver junit

经过多次搜索和阅读后,我仍然不清楚使用Webdriver处理失败断言的最佳方法。我原以为这是一个常见的核心功能。我想做的就是:

  • 寻找元素
  • 如果有的话 - 告诉我
  • 如果不在场 - 告诉我

我想为非技术受众呈现结果,因此让它使用完整堆栈跟踪抛出'NoSuchElementExceptions'是没有用的。我只想要一个好消息。

我的测试:

@Test
public void isMyElementPresent(){
  //  WebElement myElement driver.findElement(By.cssSelector("#myElement"));
    if(driver.findElement(By.cssSelector("#myElement"))!=null){
        System.out.println("My element was found on the page");
    }else{
            System.out.println("My Element was not found on the page");
        }
    }

当我强制失败时,我仍然会抛出NoSuchElementException。我还需要尝试/捕获吗?我是否可以在不需要System.out.println的情况下合并Junit断言和/或Hamcrest来生成更有意义的消息?

3 个答案:

答案 0 :(得分:9)

我遇到过类似的情况。根据{{​​1}}和findElement API的Javadoc,似乎findElements行为是设计使然。您应该使用findElement来检查不存在的元素。

因为在您的情况下,WebElement可能不存在,您应该使用findElements代替。

我会按如下方式使用它。

findElements

答案 1 :(得分:2)

你可以做些什么来检查元素是否存在

  public boolean isElementExists(By by) {
    boolean isExists = true;
    try {
        driver.findElement(by);
    } catch (NoSuchElementException e) {
        isExists = false;
    }
    return isExists;
}

答案 2 :(得分:1)

如何在try-catch中使用xPath,传递元素类型,属性和文本如下?

try {
    driver.FindElement(
        By.XPath(string.Format("//{0}[contains(@{1}, '{2}')]", 
        strElemType, strAttribute, strText)));
    return true;
}
catch (Exception) {
    return false;
}