Register @ControllerAdvice annotated Controller in JUnitTest with MockMVC

Rudolf Schmidt picture Rudolf Schmidt · Sep 1, 2014 · Viewed 19.6k times · Source

My @ControllerAdvice annotated Controller looks like this:

@ControllerAdvice
public class GlobalControllerExceptionHandler {

    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationException.class)
    public void authenticationExceptionHandler() {
    }
}

Of course my development is test driven and I would like to use my exception Handler in the JUnit Tests. My Test case looks like this:

public class ClientQueriesControllerTest {

    private MockMvc mockMvc;

    @InjectMocks
    private ClientQueriesController controller;

    @Mock
    private AuthenticationService authenticationService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void findAllAccountRelatedClientsUnauthorized() throws Exception {
        when(authenticationService.validateAuthorization(anyString())).thenThrow(AuthenticationException.class);

        mockMvc.perform(get("/rest/clients").header("Authorization", UUID.randomUUID().toString()))
                .andExpect(status().isUnauthorized());
    }
}

Probably I need to register the ControllerAdvice Class. How to do that?

Answer

Morten Berg picture Morten Berg · Nov 16, 2016

Since Spring 4.2, you can register your ControllerAdvice directly into your StandaloneMockMvcBuilder:

MockMvcBuilders
     .standaloneSetup(myController)
     .setControllerAdvice(new MyontrollerAdvice())
     .build();