TestNG:如何测试强制例外?

Chr*_*ker 18 java testng unit-testing

我想编写一个TestNG测试来确保在特定条件下抛出异常,如果没有抛出异常则测试失败.有没有必要创建一个额外的布尔变量的简单方法?

关于此主题的相关博客文章:http://konigsberg.blogspot.com/2007/11/testng-and-expectedexceptions-ive.html

Ced*_*ust 26

@Test(expectedExceptions) 对于最常见的情况很有用:

  • 您希望抛出特定的异常
  • 您需要该异常的消息才能包含特定的单词

根据文档,如果没有expectedException抛出测试将失败:

预期测试方法抛出的异常列表.如果没有异常或一个以上的这个名单上的不同被抛出,这个测试将被标记为失败.

以下是一些@Test(expectedExceptions)不充分的情况:

  • 您的测试方法有几个语句,预计只会抛出其中一个语句
  • 你抛出自己的异常类型,你需要确保它符合某个标准

在这种情况下,您应该恢复到传统的(pre-TestNG)模式:

try {
  // your statement expected to throw
  fail();
}
catch(<the expected exception>) {
  // pass
}
Run Code Online (Sandbox Code Playgroud)


har*_*han 10

使用@Test注释检查预期的异常.

@Test(
    expectedExceptions = AnyClassThatExtendsException.class,
    expectedExceptionsMessageRegExp = "Exception message regexp"
)
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想检查异常消息,只有下面就足够了

@Test(expectedExceptions = AnyClassThatExtendsException.class)
Run Code Online (Sandbox Code Playgroud)

这样,你不需要使用丑陋的try catch块,只需在测试中调用exception-thrower方法.