0

I created a class MyExceptionHandler annotated with @ControllerAdvice and @ResponseBody to handle Exceptions, as it is a common practice in Spring Boot.

Now I moved this class to a starter, that I include in several projects, so they all use the same basic exception handling. This works fine, when I start the Spring Boot application normally.

When I execute a test annotated with:

@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@WebMvcTest(controllers = SomeController.class)

The ControllerAdvice from the starter is not activated, so I can't test my error responses.

When I create a subclass of MyExceptionHandler in my project and annotate that class with @ControllerAdvice and @ResponseBody, everything works fine.

How can I ensure, that during my test, the ControllerAdvice from the starter is activated?

2 Answers2

1

I found a better way. Spring explicitly supports auto configuration for AutoConfigureWebMvc. You can add a key to /META-INF/spring.factories:

org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc=...

Also see this answer: https://stackoverflow.com/a/60247057/2936509

0
@WebMvcTest(controllers = SomeController.class)

This line is telling the test what specifically to use. Other controllers are not added to the context. @ControllerAdvice is a @Component so it is likely also not added to the context.

You should remove this specification, or add the @ControllerAdvice class you want to test as well.

The docs talks about this in the 'controllers' value and 'value' value section.

Alex
  • 710
  • 6
  • 8
  • Thanks for the pointer! Adding the advice as another "controller" in the @WebMvcTest does not work. Interestingly, when the ControllerAdvice is in the project itself, it is used. It's only not used, when it's coming from a spring-boot-starter. – Malte Finsterwalder Aug 13 '21 at 07:50
  • The documentation I find usually also states, that ControllerAdvices are added automatically, when `@WebMvcTest` is used. e.g. "By default only `@Controller` (when no explicit controllers are defined), `@ControllerAdvice` and WebMvcConfigurer beans are included." – Malte Finsterwalder Aug 13 '21 at 08:01