【问题标题】:Printing a meaningful message on test failure using jUnit, Selenium Webdriver and continuing the script使用 jUnit、Selenium Webdriver 在测试失败时打印有意义的消息并继续执行脚本
【发布时间】: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


    【解决方案1】:

    致 A)

    是的,一个解决方案是将您的第一行包装到一个 try-catch 块中。请务必捕获您期望的异常,而不要捕获其他异常,因为您的测试将包含漏洞。

    您的代码可能如下所示:

    @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)

    为您想要测试的每个案例编写单数测试。如果您将所有内容都放在一个整体测试中,那么追踪测试失败的确切位置将更加困难。编写相互依赖的测试。

    【讨论】:

    • 感谢您的回复 - 我已经尝试过建议的 try/catch 块,但仍然得到 NoSuchElementException 而没有“网页未设置”消息。不知道为什么。我同意 b) - 单一测试是要走的路
    • 尝试找到产生 NoSuchElementException 的确切行。您的 try-catch 块设置是否正确?如果是这样,请使用调试器单步执行代码,直到抛出异常。
    • 谢谢。我已经根据您的建议设置了 try/catch,并且在 currentDate = driver.find 行抛出异常............
    • 好的,很好。如果有帮助,请随时将我的帖子标记为解决方案。
    • 抱歉,我的意思是说异常仍然被抛出并且没有被处理,我没有得到很好的、有意义的消息说“页面错误”。我意识到这可能很痛苦,但正如我所提到的,我仍在学习 - 我非常感谢您的帮助。
    【解决方案2】:

    看起来您在 currentDate.IsDisplayed() 上的断言正在将布尔值(真)与字符串进行比较

    【讨论】:

      猜你喜欢
      • 2016-12-22
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多