如何使用Mockito测试方法中抛出的CustomException异常场景?
FeignException捕获后抛出CustomException的Mockito测试实现
问题描述
我已通过Mockito完成了目标方法正常返回路径的测试,现需测试该方法捕获FeignException后抛出CustomException的异常场景。以下是目标方法代码及正常路径测试代码,请问该如何实现异常测试?
目标方法代码
@Override public Response generateResponse(Request request) throws CustomException { try { GenerateResponse response = client.generateResponse(headers, generateRequest); return response; } catch (FeignException.BadRequest badRequest) { String message = "Received Bad Request"; throw new CustomException(message, "" + badRequest.status()); } catch (FeignException.Unauthorized unauthorized) { log.error(unauthorized.contentUTF8()); String message = "Received UnAuthorized Exception "; throw new CustomException(message, "" + unauthorized.status()); } }
正常路径测试代码
Mockito.when(service.getResponse(Mockito.any(), Mockito.any())).thenReturn(getResponse);
异常场景测试实现
针对两种FeignException子类的捕获场景,分别编写测试代码:
1. 测试FeignException.BadRequest场景
通过Mockito模拟FeignClient抛出FeignException.BadRequest,验证目标方法是否抛出符合预期的CustomException:
// 模拟FeignClient抛出BadRequest异常 FeignException.BadRequest badRequestEx = FeignException.badRequest("测试BadRequest", null); Mockito.when(client.generateResponse(Mockito.any(), Mockito.any())).thenThrow(badRequestEx); // 调用目标方法,捕获预期的CustomException CustomException actualEx = Assertions.assertThrows(CustomException.class, () -> { targetService.generateResponse(mockRequest); // mockRequest为预先构造的测试Request对象 }); // 验证异常的消息和状态码是否符合预期 Assertions.assertEquals("Received Bad Request", actualEx.getMessage()); Assertions.assertEquals("400", actualEx.getStatus()); // 假设CustomException有getStatus()方法获取状态码
2. 测试FeignException.Unauthorized场景
模拟FeignException.Unauthorized异常,同时验证日志是否正确输出:
// 模拟FeignClient抛出Unauthorized异常 FeignException.Unauthorized unauthorizedEx = FeignException.unauthorized("测试Unauthorized", null); Mockito.when(client.generateResponse(Mockito.any(), Mockito.any())).thenThrow(unauthorizedEx); // 调用目标方法,捕获CustomException CustomException actualEx = Assertions.assertThrows(CustomException.class, () -> { targetService.generateResponse(mockRequest); }); // 验证异常信息和状态码 Assertions.assertEquals("Received UnAuthorized Exception ", actualEx.getMessage()); Assertions.assertEquals("401", actualEx.getStatus()); // 验证日志是否正确打印了异常内容(需确保log对象已被Mock) Mockito.verify(log, Mockito.times(1)).error(unauthorizedEx.contentUTF8());
注意事项
- 确保
client和log对象已通过@Mock注解被Mockito模拟,并注入到测试的目标service中 - 使用JUnit 5的
Assertions.assertThrows捕获并验证异常,若用JUnit 4则可使用ExpectedException规则或try-catch方式 - 测试前需构造好
mockRequest等测试依赖对象
内容的提问来源于stack exchange,提问作者unknown1101
相关产品推荐
相关产品推荐

