Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Controllers Unit Test not calling @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.

Any thoughts please?.

like image 228
Arun Avatar asked Mar 08 '13 19:03

Arun


1 Answers

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.

like image 156
Matt Byrne Avatar answered Oct 18 '22 05:10

Matt Byrne