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

Java Spring引导控制器的catch块的JUnit5测试覆盖率,java,spring-boot,unit-testing,mockito,junit5,Java,Spring Boot,Unit Testing,Mockito,Junit5,我正试图用下面的代码为我的控制器编写测试。我想在catch block语句中介绍代码的测试,但我无法编写测试。我想在catch块中返回一个包含故障代码和消息的服务器响应 @PostMapping(计数器) public ResponseEntity getCounters(@Valid@RequestBody ApartmentCounterListRequestData){ 试一试{ log.debug(“为计数器列表输入API”); ApartmentCounterListResponse

我正试图用下面的代码为我的控制器编写测试。我想在catch block语句中介绍代码的测试,但我无法编写测试。我想在catch块中返回一个包含故障代码和消息的服务器响应

@PostMapping(计数器)
public ResponseEntity getCounters(@Valid@RequestBody ApartmentCounterListRequestData){
试一试{
log.debug(“为计数器列表输入API”);
ApartmentCounterListResponse ApartmentCounterListResponse=counterService.getAllCounters();
返回ResponseEntity.ok(apartmentCounterListResponse);
}捕获(异常){
log.error(“计数器列表中的异常::”,异常);
ServerResponse ServerResponse=ResponseBuilder.buildVendorFailureMessage(新的ServerResponse(),
RequestResponseCode.EXCEPTION);
返回ResponseEntity.ok(JsonResponseBuilder.inquiryresponse(serverResponse));
}
}
我的测试代码如下:

@测试
@DisplayName(“应返回带有故障数据的ServerResponse。”)
void应返回\u服务器\u响应\u对\u异常()引发异常{
/*给定*/
ApartmentCounterListRequest ApartmentCounterListRequest=ApartmentTestUtil.getApartmentCounterListRequest。
应用(“测试”、“测试”);
Mockito.when(counterServic.getAllCounters()).thenthow(newexception());
//ServerResponse ServerResponse=ApartmentTestUtil.getServerExceptionServerResponse.get();
/*然后*/
mockMvc.perform(
post(计数器URL)
.contentType(应用程序_JSON)
.content(objectMapper.writeValueAsString(apartmentCounterListRequest)))
.andExpect(状态().isOk())
.andExpect(MockMvcResultMatchers.jsonPath($.resultCode),Matchers.is(“-6”);
验证(counterService,times(1)).getAllCounters();
}
运行此测试时,出现以下错误:

org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: java.lang.Exception
我已经浏览了下面的一些帖子,但还没有找到合适的答案

有人能帮我写一个涵盖catch块的测试或者告诉我怎么做吗


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

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

您可以尝试使用
willAnswer

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

也许这有点误用,因为答案用于更复杂的for when return

是否尝试过让模拟抛出RuntimeException?没有。我试试看@斯图尔图斯克