Spring mock MVC unit test with controller advice

I am trying to test my controller advice exception handling. I have registered my controller advice to my mockmvc:

mockMvc = MockMvcBuilders.standaloneSetup(controller)
            .setControllerAdvice(new ExceptionHandlingControllerAdvice())
            .build();

I can see in the console the test is picking up the exception handling methods:

org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver Detected @ExceptionHandler methods in com.myapp...ExceptionHandlingControllerAdvice

The ExceptionHandlingControllerAdvice class has a handler method for a security exception:

@ExceptionHandler(SecurityException.class)

When my unit test throws a SecurityException, the test fails with a stacktrace instead of invoking the handler method in the controller advice.

Have I done something wrong?


Solution 1:

Annotate your Spring mock mvc test with

@ImportAutoConfiguration(YourControllerAdvice.class)

Solution 2:

If you are testing @ControllerAdvice, I would suggest not to use standalone setup, but rather load full Spring Context duting test:

Something like:

       mockMvc = MockMvcBuilders
        .webAppContextSetup(context)
        .addFilters(springSecurityFilter)
        .apply(SecurityMockMvcConfigurers.springSecurity())
        .build();