JUnit 5 中实现 JUnit 4 等价异常测试的高效方案
JUnit 5 等价异常测试的高效实现方法
你提供的JUnit 4异常测试代码,在JUnit 5中最高效且灵活的替代方案是使用Assertions.assertThrows()静态方法,它解决了JUnit 4 @Test(expected = ...)的局限性(比如无法精准定位异常抛出点、无法校验异常细节)。
转换后的JUnit 5代码
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; import static org.mockito.ArgumentMatchers.anyLong; import org.junit.jupiter.api.Test; import java.util.Optional; @Test void getRecipeByIdTestNotFound() { Optional<Recipe> recipeOptional = Optional.empty(); when(recipeRepository.findById(anyLong())).thenReturn(recipeOptional); // 验证调用指定方法时抛出NotFoundException,同时可捕获异常做额外校验 NotFoundException thrown = assertThrows(NotFoundException.class, () -> recipeService.findById(1L)); // 可选:进一步校验异常的消息、原因等属性 // assertEquals("未找到ID为1的食谱", thrown.getMessage()); }
核心优势
- 精准定位:明确指定哪段代码应该抛出异常,避免方法中其他代码提前抛出异常导致测试误通过
- 灵活扩展:捕获异常实例后,可对异常的消息、堆栈轨迹、触发原因等做更细致的验证
- 代码简洁:无需在方法上声明
throws Exception(除非测试逻辑本身需要抛出受检异常)
内容的提问来源于stack exchange,提问作者user2693135
相关产品推荐
相关产品推荐

