Skip to content
Advertisement

How to call @RestControllerAdvice class from a unit test in the Service layer of a REST web service in java?

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.

JavaScript

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.

JavaScript
Advertisement