Spring 引导控制器的 catch 块的 JUnit5 测试覆盖率

JUnit5 Test coverage for catch block of a Spring Boot Controller

我正在尝试使用以下代码为我的控制器编写测试。我想涵盖 catch 块语句中代码的测试,但我无法编写一个。我想 return 在 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

我浏览了以下一些帖子,但还没有找到合适的答案。

Java - How to Test Catch Block?

任何人都可以帮我编写涵盖 catch 块的测试或告诉我如何做吗?

我的控制器中有这个 try catch 来处理任何意外异常。对于不同的 api,我必须发送具有不同响应代码和消息的响应,这不允许我使用异常处理程序。

您正在模拟的方法没有声明已检查的异常,因此 Mockito 无法从那里抛出异常。尝试让模拟抛出未经检查的异常(即 RuntimeException)。

你可以尝试使用willAnswer

 Mockito.when(counterServic.getAllCounters()).thenAnswer(x -> {throw new Exception() });

也许这有点被误用,因为当 return

时 Answer 用于更复杂的情况