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

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

问题描述

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

有什么想法吗?.

解决方案

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

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

通过这一改进,如果您使用独立设置,那么您可以像这样设置一个或多个 ControllerAdvice 实例:

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

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

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.

Any thoughts please?.

解决方案

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

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.

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();

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天全站免登陆