【问题标题】:Selenium and AssertTrue() connectionSelenium 和 AssertTrue() 连接
【发布时间】:2013-12-18 01:03:22
【问题描述】:

我在 Eclipse/Java 中使用 Selenium,我有一个这样的 Try/Catch:

            try {
        assertTrue(selenium.isTextPresent("You Are Now Logged xxxOut"));
        System.out.println("You Are Now Logged Out is present on the web page");
        }
        catch (Throwable e) {
        System.out.println("You Are Now Logged Out is NOT present on the web page");
        }           

我想我错过了与此强制失败 (xxxOut) 的 Selenium 连接,因为如何让 Selenium 将此报告为失败?我的 TestNG 报告我的脚本运行正常,没有失败,但是如果我查看控制台,我会看到“您现在已注销,网页上不存在”,所以我确实失败了(预期的文本不存在)。

谢谢...

【问题讨论】:

    标签: java eclipse selenium


    【解决方案1】:

    既然你发现了失败,那么测试就通过了。如果您想记录您的自定义消息并仍将其报告为失败,您应该再次抛出它。在你的 sysout 后面加上 throw e ,这个 case 会被报告为失败。

    如果您不想记录自定义消息,则根本不要捕获它。

    【讨论】:

      【解决方案2】:

      首先,try/catch 块是否必要?如果被测方法都不会抛出异常,最好保持测试简单

      assertTrue(selenium.isTextPresent("You Are Now Logged xxxOut"));
      

      如果失败消息不需要输出到任何特定的输出流,但您想保留自定义消息

      String failureMsg = "You Are Now Logged Out is NOT present on the web page";
      assertTrue(selenium.isTextPresent("You Are Now Logged xxxOut"), failureMsg);
      String successMsg = "You Are Now Logged Out is present on the web page";
      System.out.println(successMsg);
      

      如果日志记录在您的测试中是绝对必要的

      try {
          assertTrue(selenium.isTextPresent("You Are Now Logged xxxOut"));
          System.out.println("You Are Now Logged Out is present on the web page");
      } catch (Throwable e) {
          String failureMsg = "You Are Now Logged Out is NOT present on the web page";
          fail(failureMsg, e)
          System.out.println(failureMsg);
      }
      

      就风格而言,我更喜欢第一种选择。除非有非常令人信服的理由将代码包装在 Try/Catch 中,否则我建议不要这样做,因为:

      1. 根据提供的 sn-p 不需要; assertTrue() 调用将抛出一个 AssertionError ,这将使测试完全失败,并且有一个允许自定义消息的重载版本
      2. 捕获所有 Throwable 实例将捕获 AssertionError 实例并导致您重新抛出它(不必要),或调用 fail()(冗余,它只是抛出一个新的 AssertionError)
      3. 重新抛出 AssertionError 以外的异常将导致测试失败并出现 Error 条件而不是 Failure 条件,这表明测试以您没有的方式失败'没有预料到,这通常被认为是一个更严重的错误

      此外,通常不建议捕获 Throwable 的实例。

      【讨论】:

      • 如果我删除了 try/catch,那么我在 TestNG 报告中看到的唯一内容是第 143 行异常错误。所以我想我可以查看源代码以查看失败的位置,但是不是很友好。如果我添加了 try/catch,我可以在控制台中记录一条消息,看看到底是什么问题。但是,我想将控制台输出保存到文件中。我确定这在 Eclipse 中是可能的,但我不知道该怎么做?
      • 关于此的另一个奇怪的事情是该行有效(它强制失败并且我在控制台中得到指向第 143 行的空指针异常:assertTrue(selenium.isTextPresent("You Are Now Logged) xxxOut")); 但是这条线通过了,它不应该: assertEquals("You Are Now Logged Out", driver.getPageSource().contains("You Are Now Logged xxxOut")); 我不知道为什么这条线通过?
      猜你喜欢
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 2021-03-23
      相关资源
      最近更新 更多