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

时间:2021-05-20 06:12:14

标签: java spring-boot unit-testing mockito 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

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

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,我必须使用不同的响应代码和消息发送响应,这不允许我使用异常处理程序。

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:0)

您可以尝试使用 willAnswer

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

也许这有点误用,因为 Answer 用于更复杂的返回时间