【发布时间】:2021-08-09 09:09:08
【问题描述】:
我正在尝试使用以下代码为我的控制器编写测试。我想涵盖对 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
我浏览了以下一些帖子,但还没有找到合适的答案。
Unit testing code in catch block of a Spring Controller
Java - How to Test Catch Block?
Unit testing code in catch block of a Spring Controller
JUnit for both try and catch block coverage
谁能帮我写一个覆盖catch块的测试或者告诉我怎么做?
我的控制器中有这个 try catch 来处理任何意外异常。对于不同的 api,我必须发送带有不同响应代码和消息的响应,这不允许我使用异常处理程序。
【问题讨论】:
-
你试过让你的 mock 抛出 RuntimeException 吗?
-
不,我没有。我会试试看。 @Stultuske
标签: java spring-boot unit-testing mockito junit5