为本地@ExceptionHandler编写JUnit测试 [英] Write JUnit test for local @ExceptionHandler

查看:70
本文介绍了为本地@ExceptionHandler编写JUnit测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下控制器:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆