java - Spring Boot Controller 的 catch 块的 JUnit5 测试覆盖率
问题描述
我正在尝试使用下面的代码为我的控制器编写测试。我想涵盖对 catch 块语句中代码的测试,但我无法编写一个。我想在 catch 块中返回带有失败代码和消息的服务器响应。
@PostMapping(COUNTERS)
public ResponseEntity<?> getCounters(@Valid @RequestBody ApartmentCounterListRequest requestData) {
try {
log.debug("Entering API for counter list");
ApartmentCounterListResponse apartmentCounterListResponse = counterService.getAllCounters();
return ResponseEntity.ok(apartmentCounterListResponse);
} catch (Exception exception) {
log.error("Exception in counter list :: ", exception);
ServerResponse serverResponse = ResponseBuilder.buildVendorFailureMessage(new ServerResponse(),
RequestResponseCode.EXCEPTION);
return ResponseEntity.ok(JsonResponseBuilder.enquiryResponse(serverResponse));
}
}
我的测试代码如下:
@Test
@DisplayName("Should return ServerResponse with failure data.")
void Should_Return_Server_Response_On_Exception() throws Exception {
/*given*/
ApartmentCounterListRequest apartmentCounterListRequest = ApartmentTestUtil.getApartmentCounterListRequest.
apply("test", "test");
Mockito.when(counterServic.getAllCounters()).thenThrow(new Exception());
// ServerResponse serverResponse = ApartmentTestUtil.getServerExceptionServerResponse.get();
/*then*/
mockMvc.perform(
post(COUNTER_URL)
.contentType(APPLICATION_JSON)
.content(objectMapper.writeValueAsString(apartmentCounterListRequest)))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.resultCode", Matchers.is("-6")));
verify(counterService, times(1)).getAllCounters();
}
当我运行此测试时,我收到以下错误:
org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: java.lang.Exception
我浏览了以下一些帖子,但还没有找到合适的答案。
Spring Controller 的 catch 块中的单元测试代码
Spring Controller 的 catch 块中的单元测试代码
任何人都可以帮我编写涵盖 catch 块的测试或告诉我如何做吗?
我的控制器中有这个 try catch 来处理任何意外的异常。对于不同的 api,我必须发送带有不同响应代码和消息的响应,这不允许我使用异常处理程序。
解决方案
您正在模拟的方法没有声明已检查的异常,因此 Mockito 无法从那里抛出一个异常。尝试让 mock 抛出未经检查的异常(即 RuntimeException)。
推荐阅读
- mysql - Spring Boot War 文件未连接到 kubernetes 中的 MySQL 数据库?
- java - JPA 不会将关联对象保存在 @RequestBody 注释获取的对象中
- pytorch - 如何用pytorch将多标签分类上下文下的标签列表覆盖为one-hot编码?
- python - 如何从 Python 中的所有行和列数组中找到单个最大值并显示其行和列索引
- gradle - Gradle - Dependencies between test directories
- laravel-5.8 - SQLSTATE [23000]:违反完整性约束:1048 列“product_id”不能为空(SQL:插入“category_product”)
- c# - 如何构造 SQL 查询 where 字段 IN 子查询?
- jenkins - Jenkins Pipeline:成功构建和上传存档后在 Git 存储库中创建标签
- google-kubernetes-engine - Increase IP space of existing GKE cluster
- javascript - “加载失败”事件的反面是什么