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

Tags: ,

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.

public class ServiceTest {

  private Service testService = new ServiceImpl();

  private Repository repository; 

  public void testException() {
        Exception.class, ()->{
          // Code that throws exception.

public class ExceptionHandler {

  public ResponseEntity<Object> handleUnknownException(Exception ex) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
               .body("Body Here");



@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)

Source: stackoverflow