原文: https://howtodoinjava.com/junit5/expected-exception-example/
在 JUnit5 中,要测试异常情况,则应使用org.junit.jupiter.api.Assertions.assertThrows()方法。 JUnit5 异常测试还有其他方法,但我建议避免使用它们。
1. JUnit5 assertThrows()的语法
它断言所提供的executable的执行将引发expectedType的异常并返回该异常。
public static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable)
如果没有引发异常,或者引发了其他类型的异常,则此方法将失败。
请注意,允许使用相同类型的异常。 例如,如果您期望NumberFormatException并且抛出IllegalArgumentException,那么该测试也会通过,因为NumberFormatException扩展了IllegalArgumentException类。
2. JUnit5 预期异常示例
一个非常简单的示例可以是:
@Testvoid testExpectedException() {Assertions.assertThrows(NumberFormatException.class, () -> {Integer.parseInt("One");});}
如果参数不是有效数字,则此处的可执行代码为Integer.parseInt("One")引发NumberFormatException。 在上述代码中,"One"不是有效数字,因此代码将引发assertThrows()方法所期望的异常 - 因此测试通过。
3. 预期异常类的超类型
如前所述,您也可以期望异常类的超类型。 例如,上面的测试也可以用IllegalArgumentException编写。
@Testvoid testExpectedExceptionWithSuperType() {Assertions.assertThrows(IllegalArgumentException.class, () -> {Integer.parseInt("One");});}
该测试用例也将通过。
4. 其他预期异常类
如果可执行代码抛出任何其他异常类型,则测试将失败;否则,测试将失败。 甚至如果测试没有引发任何异常,那么测试也会失败。
例如,在下面的示例中,"1"是有效数字,因此不会引发异常。
@Testvoid testExpectedExceptionFail() {Assertions.assertThrows(IllegalArgumentException.class, () -> {Integer.parseInt("1");});}
5. 完整的例子
这是 JUnit5 断言异常消息的完整代码。
package com.howtodoinjava.junit5.examples.module;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;public class AppTest {@Testvoid testExpectedException() {Assertions.assertThrows(NumberFormatException.class, () -> {Integer.parseInt("One");});}@Testvoid testExpectedExceptionWithSuperType() {Assertions.assertThrows(IllegalArgumentException.class, () -> {Integer.parseInt("One");});}@Testvoid testExpectedExceptionFail() {Assertions.assertThrows(IllegalArgumentException.class, () -> {Integer.parseInt("1");});}}
现在,使用测试套件执行此类。 您可以在 maven 示例中查看完整的项目配置。
package com.howtodoinjava.junit5.examples;import org.junit.platform.runner.JUnitPlatform;import org.junit.platform.suite.api.SelectPackages;import org.junit.runner.RunWith;@RunWith(JUnitPlatform.class)@SelectPackages("com.howtodoinjava.junit5.examples")public class JUnit5Example{}
Eclipse 测试结果如下图所示:

JUnit5 预期异常测试
这就是 JUnit5 异常测试的全部。 将我的问题放在评论部分。
学习愉快!
