MockMVC how to test exception and response code in the same test case

If you have an exception handler and you want to test for a specific exception, you could also assert that the instance is valid in the resolved exception.

.andExpect(result -> assertTrue(result.getResolvedException() instanceof WhateverException))

UPDATE (gavenkoa) Don’t forget to inject @ExceptionHandler annotated methods to the test context or exception will occur at .perform() instead of capturing it with .andExpect(), basically register:

@ControllerAdvice
public class MyExceptionHandlers {
    @ExceptionHandler(BindException.class)
    public ResponseEntity<?> handle(BindException ex) { ... }
}

with @Import(value=...) or @ContextConfiguration(classes=...) or by other means.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)