junit 5测试异常处理
在JUnit中,有3种流行的方式来处理测试代码中的异常:
- 试捕习语
- 使用JUnit规则
- 带注解
试捕习语
这个习语是最受欢迎的习语之一,因为它已在JUnit 3中使用。
@Test
public void throwsExceptionWhenNegativeNumbersAreGiven() {
try {
calculator.add("-1,-2,3");
fail("Should throw an exception if one or more of given numbers are negative");
} catch (Exception e) {
assertThat(e)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("negatives not allowed: [-1, -2]");
}
}
上面的方法是一种常见的模式。 当没有引发异常并且在catch子句中验证了异常本身时,测试将失败(在上面的示例中,我使用了FEST Fluent断言),尽管它很好,但我更喜欢使用
ExpectedException规则。
使用JUnit规则
可以使用创建相同的示例
ExceptedException规则。 规则必须是标有@Rule批注的公共字段。 请注意,“抛出”规则可能会在许多测试中重复使用。
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void throwsExceptionWhenNegativeNumbersAreGiven() {
// arran