经过多次搜索和阅读后,我仍然不清楚使用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来生成更有意义的消息?
答案 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;
}