Testing Spring MVC @ExceptionHandler method with Spring MVC Test

C0deAttack picture C0deAttack · May 21, 2013 · Viewed 57.3k times · Source

I have the following simple controller to catch any unexpected exceptions:

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseEntity handleException(Throwable ex) {
        return ResponseEntityFactory.internalServerErrorResponse("Unexpected error has occurred.", ex);
    }
}

I'm trying to write an integration test using Spring MVC Test framework. This is what I have so far:

@RunWith(MockitoJUnitRunner.class)
public class ExceptionControllerTest {
    private MockMvc mockMvc;

    @Mock
    private StatusController statusController;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(new ExceptionController(), statusController).build();
    }

    @Test
    public void checkUnexpectedExceptionsAreCaughtAndStatusCode500IsReturnedInResponse() throws Exception {

        when(statusController.checkHealth()).thenThrow(new RuntimeException("Unexpected Exception"));

        mockMvc.perform(get("/api/status"))
                .andDo(print())
                .andExpect(status().isInternalServerError())
                .andExpect(jsonPath("$.error").value("Unexpected Exception"));
    }
}

I register the ExceptionController and a mock StatusController in the Spring MVC infrastructure. In the test method I setup an expectation to throw an exception from the StatusController.

The exception is being thrown, but the ExceptionController isn't dealing with it.

I want to be able to test that the ExceptionController gets exceptions and returns an appropriate response.

Any thoughts on why this doesn't work and how I should do this kind of test?

Thanks.

Answer

Brian Matthews picture Brian Matthews · Oct 23, 2015

I just had the same issue and the following works for me:

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.standaloneSetup(statusController)
         .setControllerAdvice(new ExceptionController())
        .build();
}