Benoit BERAUD opened SPR-17542 and commented
MockMvcBuilders is supposed to support any kind of @ControllerAdvice (see #17348, especially last comment from Rossen Stoyanchev).
Indeed it seems to work only with ExceptionHandlers.
See attached file for a test which succeeds (ExceptionHandlerTests, copied from Spring source code) and a failing test (GenericControllerAdviceTests, creation of my own). Files are also present here : https://gist.github.com/benoit74/651a9348120613e42b0e2ee4894a6e5e
Bug seems to be present since the implementation of #17348 (for instance bug seen in Spring Boot 1.5.17, e.g. Spring 4.3.20). A backport to 4.3 would be greatly appreciated (even if EOL is quite close ...).
Affects: 5.1.2
Attachments: - controllerAdvice.zip (23.11 kB)
Issue Links:
- #17348 Support @ControllerAdvice registrations in the MockMvcBuilders standalone setup
Comment From: spring-projects-issues
Rossen Stoyanchev commented
Thanks for the sample test. However @ControllerAdvice is working as expected. I don't believe there is an issue. The problem rather is that the controller is neither @RestController, nor has @ResponseBody and therefore the ResponseBodyAdvice does not apply. The test is green if @RestController or @ResponseBody is used.
Comment From: spring-projects-issues
Benoit BERAUD commented
So obvious. Sorry for your time lost on such a mistake.
Comment From: spring-projects-issues
Benoit BERAUD commented
Indeed, looking back at my original project (not the test sample I provided), I realised that I was already using a @RestController.
My issue was indeed that I returned a ResponseEntity without any body to "simplify" my test :
return ResponseEntity.ok().build();
If change this to return a body, the test is green:
return ResponseEntity.ok("whatever");
Too bad ...
Comment From: metodski
What if i have @ControllerAdvice on a whole package and don't want to add the controller classes one by one in the standaloneSetup ?