FMC
FMC

Reputation: 660

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?

Upvotes: 3

Views: 6751

Answers (2)

Ali Baba
Ali Baba

Reputation: 123

Annotate your Spring mock mvc test with

@ImportAutoConfiguration(YourControllerAdvice.class)

Upvotes: 8

luboskrnac
luboskrnac

Reputation: 24591

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

Upvotes: 1

Related Questions