@ControllerAdvice 未在单元测试中触发

@ControllerAdvice not triggered on unit testing

我需要测试服务层中的@ControllerAdvice 方法。但我遇到了两个问题:

  1. 未触发异常处理程序
  2. 即使它会被触发,我发现现在还不知道如何测试它)

@Slf4j @ControllerAdvice public class AppExceptionHandler {

@ExceptionHandler(value = {.class})
public ResponseEntity<Object> handleMyException(MyException ex, WebRequest request) {
ErrorMessage errorMessage = ErrorMessage.builder()
   .message(ex.getMessage())
   .httpStatus(HttpStatus.BAD_REQUEST)
   .time(ZonedDateTime.now())
   .build();
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);

}

@RunWith(MockitoJUnitRunner.class)
@RequiredArgsConstructor
public class MyExceptionTest {

   private final AppExceptionHandler handler;
   @Mock private final MyService service;

   @Test
   public void test() throws MyException {
      when(service.create(any()))
          .thenThrow(MyException .class);
   }
}

为此,您可以使用 @WebMvcTest 为您的控制器层编写一个测试,因为这个 will create a Spring Test Context 包含所有 @ControllerAdvice.

由于您的服务抛出此异常,您可以使用 @MockBean 模拟服务 bean 并使用 Mockito 指示您的 bean 抛出预期的异常。

由于我不知道你的控制器长什么样,下面是一个基本的例子:

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
class PublicControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @MockBean
  private MyService myService;
  
  @Test
  public void testException() throws Exception {
    when(myService.create(any())).thenThrow(new MyException.class);
    
    this.mockMvc
      .perform(get("/public"))
      .andExpect(status().isBadRequest());
  }
}