为本地@ExceptionHandler编写JUnit测试 [英] Write JUnit test for local @ExceptionHandler
问题描述
我有以下控制器:
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) {}
}
我的目标是,如果证书无效,该控制器将重定向到异常处理程序.
My goal is to that controller redirects to exception handler if certificate is not valid.
推荐答案
使用standaloneSetup
时,您所做的就是为特定控制器执行设置.
When using standaloneSetup
all you are doing is performing the setup for the specific controller.
如果您不想配置整个应用程序上下文(可以使用webAppContextSetup
而不是standaloneSetup
进行配置),则可以通过将代码更改为以下内容来手动设置异常处理程序:
If you don't want to configure the whole application context (which you would do with webAppContextSetup
instead of standaloneSetup
), you can manually setup the exception handler by changing your code to:
@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
批注
This works because ExceptionHandlerExceptionResolver is the class that Spring MVC uses to handle exceptions based on the @ExceptionHandler
annotation
查看我较早的相关答案中的一个,其中涵盖了越来越困难的情况(在计算机上使用@ControllerAdvice
包含@ExceptionHandler
的类.
Check out one of my older relevant answers that covers an ever more difficult case (the use of @ControllerAdvice
on a class that contains @ExceptionHandler
).
这篇关于为本地@ExceptionHandler编写JUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!