经过大量搜索和阅读后,我仍然不清楚使用 Webdriver 处理失败断言的最佳方法。我本以为这是一个常见且核心的功能。我想做的就是:
- 寻找一个元素
- 如果在场 - 告诉我
- 如果不在场 - 告诉我
我想向非技术受众展示结果,因此让它抛出带有完整堆栈跟踪的“NoSuchElementException”并没有帮助。我只是想要一条好消息。
My test:
@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 。我还需要尝试/捕获吗?我可以合并 Junit 断言和/或 Hamcrest 来生成更有意义的消息,而不需要 System.out.println 吗?
我也遇到过类似的情况。根据Javadoc https://seleniumhq.github.io/selenium/docs/api/java/为了findElement
and findElements
API,看来findElement
行为是设计使然的。你应该使用findElements
检查不存在的元素。
由于在您的情况下,WebElement 可能不存在,因此您应该使用findElements
反而。
我会按如下方式使用它。
List<WebElement> elems = driver.findElements(By.cssSelector("#myElement"));
if (elems.size == 0) {
System.out.println("My element was not found on the page");
} else
System.out.println("My element was found on the page");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)