assertThrows是JUnit 5中验证异常的推荐方式,可精准捕获异常类型、消息及自定义字段;需确保引入junit-jupiter依赖,用法包括断言异常类型、消息和嵌套属性。

在单元测试中使用 assertThrows 是验证代码是否按预期抛出指定异常的最直接、最推荐的方式。它属于 JUnit 5(org.junit.jupiter.api.Assertions)提供的断言方法,能精准捕获异常类型、检查异常消息,并支持后续对异常对象的进一步断言。
确认使用的是 JUnit 5
确保项目依赖的是 JUnit 5(而非 JUnit 4),因为 assertThrows 在 JUnit 4 中不存在。Maven 中应引入:
<dependency><groupid>org.junit.jupiter</groupid><artifactid>junit-jupiter</artifactid><version>5.10.2</version><scope>test</scope></dependency>
基本用法:捕获并断言异常类型
最常见场景是验证某段代码是否抛出了特定类型的异常:
- 传入期望的异常类(如
IllegalArgumentException.class)和一个Executable(即要执行的 lambda 表达式) - 方法返回捕获到的异常实例,可用于后续校验
示例:
@Test
void whenNegativeAge_thenThrowIllegalArgumentException() {
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> new Person(-5) // 构造函数内部 throw new IllegalArgumentException("age must be positive")
);
assertEquals("age must be positive", exception.getMessage());
}校验异常消息(message)
仅检查异常类型不够严谨,通常还需验证异常消息是否符合预期:
- 调用
assertThrows获取异常对象后,直接对其getMessage()或getCause()做断言 - 也可结合
assertTrue(exception.getMessage().contains("..."))做模糊匹配
注意:避免只断言 exception != null,这无法保证是目标异常类型。
处理嵌套异常或自定义异常字段
若自定义异常包含额外字段(如错误码 errorCode),可继续断言:
MyBusinessException exception = assertThrows(
MyBusinessException.class,
() -> service.process(invalidInput)
);
assertEquals("ERR_001", exception.getErrorCode());
assertEquals(400, exception.getHttpStatus());
这种写法比 @Test(expected = ...)(JUnit 4)更灵活,也比手动 try-catch 更简洁安全。










