【发布时间】:2014-02-02 07:07:42
【问题描述】:
请原谅初学者的问题。我有一个 Webdriver 脚本(Java、JUnit4),它测试了许多非常相似的网页的常见元素。
有些网页上有日期,有些则没有。对于那些不这样做的人,我希望测试结果打印“不显示当前日期”,然后继续运行 @Test 的其余部分。
我正在使用的代码 sn-p:
@Test
public void checkIfTodaysDateDisplayed(){
WebElement currentDate = driver.findElement(By.cssSelector(".currentDate"));
assertEquals("The current date is not displayed", currentDate.isDisplayed());
}
目前,在那些不包含日期的页面上,会抛出 NoSuchElementException 并且 Jenkins 测试结果仅显示:“无法定位元素:{“方法”:“css选择器”,“选择器”:“.currentDate “}”
我想要实现的是: a) 打印有意义的信息 b) 不要停止测试,因为我需要为每个页面运行 5 或 6 个其他 @Test。
修复断言并处理此问题的最佳/最佳解决方案是什么? Try/Catch 块?
编辑:更新代码:
WebElement currentDate = null;
try {
currentDate = driver.findElement(By.cssSelector(".currentDate"));
} catch (NoSuchElementException e) {
Assert.fail("The current date is not displayed! " + e.getMessage());
}
Assert.assertNotNull(currentDate);
Assert.assertEquals("The current date is displayed", currentDate.isDisplayed());
如果页面有日期,控制台会打印:
java.lang.AssertionError:
Expected :The current date is displayed
Actual :true
如果页面没有日期,控制台会打印:
org.openqa.selenium.NoSuchElementException: Unable to locate element:
{"method":"css selector","selector":".currentDate"}
【问题讨论】:
标签: java selenium junit jenkins hamcrest