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.
Here is the outline of the class: @Controller public class MyController{ @RequestMapping(..) public void myMethod(...) throws NotAuthorizedException{...} @ExceptionHandler(NotAuthorizedException.
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With