我有以下控制器:
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());
}
这有效是因为异常处理器异常解析器 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.html是Spring MVC用来处理异常的类@ExceptionHandler
注解
查看one https://stackoverflow.com/a/25604448/2504224我较早的相关答案涵盖了一个更加困难的情况(使用@ControllerAdvice
在包含的类上@ExceptionHandler
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)