title: Testing Spring MVC @ExceptionHandler method with Spring MVC Test
body: <p>I have the following simple controller to catch any unexpected exceptions:</p>
  
  <pre><code>@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);
      }
  }
  </code></pre>
  
  <p>I'm trying to write an integration test using Spring MVC Test framework. This is what I have so far:</p>
  
  <pre><code>@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"));
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>The exception is being thrown, but the ExceptionController isn't dealing with it.</p>
  
  <p>I want to be able to test that the ExceptionController gets exceptions and returns an appropriate response.</p>
  
  <p>Any thoughts on why this doesn't work and how I should do this kind of test?</p>
  
  <p>Thanks.</p>