I have a REST webservice application. I am handling exceptions by exception handler using the annotation @ExceptionHandler and @RestControllerAdvice. My exceptions are thrown in the Service layer. Now I am writing unit tests for the service layer. I am checking the exceptions using Assert.assertThrows. The exception is thrown, and the test passes. However, the exception handler method is not called when an exception is thrown. I need the exception handler method to be called during the unit test. Test class and the ExceptionHandler class are like the following.
@RunWith(SpringRunner.class) public class ServiceTest { @InjectMocks private Service testService = new ServiceImpl(); @Mock private Repository repository; @Test public void testException() { assertThrows( Exception.class, ()->{ // Code that throws exception. }); } } @RestControllerAdvice public class ExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<Object> handleUnknownException(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("Body Here"); } }
Advertisement
Answer
@RestControllerAdvice is kind of interceptor of exceptions thrown by class annotated with @RestController, that’s why exception handler method is not being invoked for your test schenario.
To test that, you should write a test for your the controller, Use the mockMvc and register your exceptionHandler class with it like below. hope, it helps.
this.mockMvc = MockMvcBuilders.standaloneSetup(new YourController()).setControllerAdvice(ExceptionHandler.class) .build();