Selenium和AssertTrue()连接

时间:2013-12-18 01:03:23

标签: java eclipse selenium

我在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报告我的脚本运行正常而没有失败,但是如果我看到控制台,我看到“你现在已经注销了网页上没有”,所以我确实失败了(预期的文本不在那里)。 / p>

...谢谢

2 个答案:

答案 0 :(得分:1)

由于您已经发现故障,测试已经过去了。如果要记录自定义消息并仍然将其报告为失败,则应再次抛出。在sysout之后添加throw e,并且该情况将被报告为失败。

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

答案 1 :(得分:0)

首先,是否需要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. 根据提供的代码段没有必要; assertTrue()调用将抛出一个AssertionError,它将彻底失败测试并且有一个允许自定义消息的重载版本
  2. 捕获所有Throwable实例将捕获AssertionError实例并导致您重新抛出它(不必要),或调用fail()(冗余,它只会抛出一个新的AssertionError)
  3. 重新抛出除AssertionError之外的异常将导致测试失败并显示错误条件而不是失败条件,表明测试失败的方式与您没有预计,这通常被认为是一个更严重的错误
  4. 此外,通常不建议捕获Throwable的实例。