我有以下控制器:

class Controller {

    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/verifyCert", method = RequestMethod.GET)
    public void verifyCertificate() throws CertificateExpiredException, CertificateNotYetValidException {
        certificate.checkValidity();
    }

    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler({CertificateExpiredException.class, CertificateNotYetValidException.class})
    public void handleCertificateValidityException(Exception e) {}
}

我的目标是,如果证书无效,该控制器将重定向到异常处理程序。

最佳答案

使用standaloneSetup时,您要做的就是为特定控制器执行设置。

如果您不想配置整个应用程序上下文(用webAppContextSetup而不是standaloneSetup来完成),则可以通过将代码更改为以下内容来手动设置异常处理程序:

 @Before
 public void setup() throws IOException {
     MockitoAnnotations.initMocks(this);
     mockMvc = MockMvcBuilders.standaloneSetup(controller).setHandlerExceptionResolvers(new ExceptionHandlerExceptionResolver()).build();
 }

 @Test
 public void test() throws Exception {
     mockMvc.perform(get("/verifyCert.controller").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andExpect(status().isForbidden());
 }

这是可行的,因为ExceptionHandlerExceptionResolver是Spring MVC用于根据@ExceptionHandler批注处理异常的类

请查看我较早的相关答案中的one,它涵盖了越来越困难的情况(在包含@ControllerAdvice的类上使用@ExceptionHandler)。

08-17 11:36