Spring MVC控制器单元测试未调用@ControllerAdvice [英] Spring MVC Controllers Unit Test not calling @ControllerAdvice

查看:79
本文介绍了Spring MVC控制器单元测试未调用@ControllerAdvice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中有一组控制器,并有一个注释为@ControllerAdvice的类,该类设置在每个这些控制器中使用的某些数据元素.我正在使用Spring MVC 3.2,并具有这些控制器的Junits.当我运行Junit时,如果我将应用程序部署在Tomcat中并通过浏览器提交请求,则该控件不会转到ControllerAdvice类,那么它可以正常工作.

I have a set of Controllers in the application and a class annotated as @ControllerAdvice which sets up certain data elements that are used in each of these controllers. I'm using Spring MVC 3.2 and have Junits for these controllers. When I run the Junit the control is not going to the ControllerAdvice class wheres it works fine if I deploy the app in Tomcat and submit a request through browser.

有什么想法吗?.

推荐答案

使用@ eugene-to和其他类似的答案后在这里,我发现了一些限制,并在Spring上提出了一个问题: https://jira.spring. io/browse/SPR-12751

After using the answer from @eugene-to and another similar one here I found limitations and raised an issue on Spring: https://jira.spring.io/browse/SPR-12751

结果,Spring测试引入了在4.2中的构建器中注册@ControllerAdvice类的功能.如果您使用的是 Spring Boot ,则需要1.3.0或更高版本.

As a result, Spring test introduced the ability to register @ControllerAdvice classes in the builder in 4.2. If you are using Spring Boot then you will need 1.3.0 or later.

有了这项改进,如果您使用的是独立安装程序,则可以像这样设置一个或多个ControllerAdvice实例:

With this improvement, if you are using standalone setup then you can set one or more ControllerAdvice instances like so:

mockMvc = MockMvcBuilders.standaloneSetup(yourController)
            .setControllerAdvice(new YourControllerAdvice())
            .build();

注意:名称setControllerAdvice()可能不会立即使它变得明显,但是您可以将许多实例传递给它,因为它具有var-args签名.

Note: the name setControllerAdvice() may not make it immediately obvious but you can pass many instances to it, since it has a var-args signature.

这篇关于Spring MVC控制器单元测试未调用@ControllerAdvice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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