如何为 GlobalExceptionHandler ControllerAdvice 编写 Spring 引导测试用例

How to write Spring boot test case for GlobalExceptionHandler ControllerAdvice

我有一个如下所示的异常处理程序:

@ControllerAdvice
public class GlobalExceptionHandlerController{
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ResponseEntity<CustomErrorResponse> handleGenericNotFoundException(NoHandlerFoundException e,WebRequest req) {
        CustomErrorResponse error = new CustomErrorResponse("NOT_FOUND_ERROR", e.getMessage());
        error.setTimestamp(LocalDateTime.now());
        error.setStatus((HttpStatus.NOT_FOUND.value()));
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }   

}

我不知道从哪里开始,我在其他 class 中进行了一些测试,它抛出 NoHandlerException 但是当我检查 junit 覆盖率时,handleGenericNotFoundException 没有突出显示。

我对 GlobalException 的测试 class 如下:

@SpringBootTest
@RunWith(SpringRunner.class)
class GlobalExceptionTest{
   @InjectMocks
   GlobalExceptionHandlerController gxhc;
   @Mock 
   WebRequest req;

   @Test(expected=NoHandlerMethodFoundException.class)
   public void throwNotFoundException() throws NoHandlerMethodFoundException{
       throw new NoHandlerMethodFoundException("POST","http:localhost",httpHeaders);
  }
}

不要在测试中抛出异常,而是将其作为参数传递给异常处理程序,然后验证结果:

public class GlobalExceptionHandlerControllerTest {

    private final GlobalExceptionHandlerController handler = new GlobalExceptionHandlerController();

    @Test
    public void handleGenericNotFoundException() {
        NoHandlerMethodFoundException e = new NoHandlerMethodFoundException("POST", "http:localhost", httpHeaders);
        ResponseEntity<CustomErrorResponse> result = handler.handleGenericNotFoundException(e);
        assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
    }
}