首页 > 解决方案 > 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 块中的单元测试代码

Java - 如何测试 Catch 块?

Spring Controller 的 catch 块中的单元测试代码

用于 try 和 catch 块覆盖的 JUnit

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

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

标签: javaspring-bootunit-testingmockitojunit5

解决方案


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


推荐阅读