请原谅初学者的问题。我有一个 Webdriver 脚本(Java、JUnit4),它测试许多非常相似的网页的常见元素。
有些网页上有日期,有些则没有。对于那些不这样做的人,我希望测试结果打印“当前日期未显示”,然后继续运行 @Test 的其余部分。
我正在使用的代码片段:
@Test
public void checkIfTodaysDateDisplayed(){
WebElement currentDate = driver.findElement(By.cssSelector(".currentDate"));
assertEquals("The current date is not displayed", currentDate.isDisplayed());
}
目前,在那些不包含日期的页面上,会抛出 NoSuchElementException ,并且 Jenkins 测试结果只是显示:“无法定位元素:{"method":"css 选择器","selector":".currentDate “}”
我想要实现的是: a) 打印一条有意义的消息 b) 不要停止测试,因为我需要为每个页面运行 5 或 6 个其他 @Test。
修复断言并处理此问题的最佳/最佳解决方案是什么? Try/Catch block ?
编辑:更新的代码:
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"}
最佳答案
致A)
是的,一个解决方案是将第一行包装到 try-catch block 中。确保仅捕获您期望的异常,而不捕获其他异常,因为您的测试将包含漏洞。
您的代码可能如下所示:
@Test
public void checkIfTodaysDateDisplayed(){
WebElement currentDate = null;
try {
currentDate = driver.findElement(By.cssSelector(".currentDate"));
}
catch (NoSuchElementException e) {
Assert.fail("Web page is not properly set up! " + e.getMessage());
}
Assert.assertNotNull(currentDate);
Assert.assertEquals("The current date is not displayed", currentDate.isDisplayed());
}
您可能希望将其他信息附加到您的断言中,例如异常堆栈跟踪或调试所需的任何信息。
致B)
为您想要测试的每个案例编写单一测试。如果您将所有内容都放在一个整体测试中,那么追踪测试失败的确切位置就会变得更加困难。编写不相互依赖的测试。
关于java - 使用 jUnit、Selenium Webdriver 打印有关测试失败的有意义的消息并继续执行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21109893/