1.介绍
在本快速教程中,我们将研究如何使用JUnit库测试是否抛出了异常。
当然,我们将确保涵盖JUnit 4和JUnit 5版本。
进一步阅读:
2.JUnit 5
JUnit 5 Jupiter断言API引入了assertThrows用于断言异常的方法。
它接受预期异常的类型和可执行的函数式接口,我们可以通过lambda表达式通过测试代码:
@Test public void whenexceptionthrown_thenassertionsucces() {Exception Exception = assertThrows(NumberFormatException.class, () -> {Integer.parseInt("1a");});String expectedMessage = "For input String ";String actualMessage = exception.getMessage();assertTrue (actualMessage.contains (expectedMessage));}
如果抛出预期的异常,assertThrows返回异常,使我们能够对消息进行断言。
此外,需要注意的是当所包含的代码抛出类型异常时,该断言得到满足NullPointerException或者它的任何派生类型。
这意味着如果我们通过了异常作为预期的异常类型,抛出的任何异常都将使断言成功,因为异常是所有异常的超类型。
如果我们把上面的测试改为aRuntimeException,这也会过去:
@Test public void whenDerivedExceptionThrown_thenAssertionSucceds() {Exception Exception = assertThrows(RuntimeException.class, () -> {Integer.parseInt("1a");});String expectedMessage = "For input String ";String actualMessage = exception.getMessage();assertTrue (actualMessage.contains (expectedMessage));}
的assertThrows ()方法允许对异常断言逻辑进行更细粒度的控制,因为我们可以使用它围绕着代码的特定部分。
3.JUnit 4
当使用JUnit 4时,我们可以简单地使用预期的属性@Test注释声明我们期望在带注释的测试方法的任何地方抛出异常。
因此,当测试运行时,如果指定的异常没有被抛出,它将失败,如果被抛出,它将通过:
@Test(expected = NullPointerException.class) public void whenExceptionThrown_thenExpectationSatisfied() {String test = null;test.length ();}
在这个例子中,我们已经声明了我们期望我们的测试代码会导致NullPointerException。
如果我们只对断言抛出异常感兴趣,这就足够了。
当需要验证异常的其他属性时,可以使用ExpectedException规则。
让我们看一个验证消息异常的属性:
@Rule public ExpectedException exceptionRule = ExpectedException.none();@Test public void whenExceptionThrown_thenRuleIsApplied() {exceptionRule.expect(NumberFormatException.class);exceptionRule。expectMessage(“输入字符串”);Integer.parseInt (" 1 ");}
在上面的例子中,我们首先声明ExpectedException规则。然后在我们的测试中,我们断言试图解析整数值将导致NumberFormatException与消息" For input string "
4.结论
在本文中,我们讨论了JUnit 4和JUnit 5的异常断言。
示例的完整源代码是可用的在GitHub。