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.