Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Spring MVC @ExceptionHandler method with Spring MVC Test

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.

like image 958
C0deAttack Avatar asked May 21 '13 11:05

C0deAttack


People also ask

How do you write JUnit for ExceptionHandler?

Here is the outline of the class: @Controller public class MyController{ @RequestMapping(..) public void myMethod(...) throws NotAuthorizedException{...} @ExceptionHandler(NotAuthorizedException.

Which class is used to test Spring MVC REST Web application?

We create the test data by using a test data builder class. Configure our mock object to return the created test data when its findAll() method is invoked.


1 Answers

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(); } 
like image 83
Brian Matthews Avatar answered Sep 17 '22 17:09

Brian Matthews