Search code examples
javaspring-bootexceptionhandlercontroller-advice

Java Test for Spring ExceptionalHandler


I have a springboot project with controllers and servies. And a GlobalExceptionHandler like -

public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
 @ExceptionHandler(DataIntegrityViolationException.class)
  public ResponseEntity<Object> handle(DataIntegrityViolationException e, WebRequest request) {
    ....

     String requestPath = ((ServletWebRequest)request).getRequest().getRequestURI();

    // I am using this requestPath in my output from springboot
   ...

  }
}

Can someone please tell me how to write mock this in my unit test class ((ServletWebRequest)request).getRequest().getRequestURI()


Solution

  • Unfortunately there is no support for subbing final methods in Mockito. You can use a other mocking framework like PowerMock.

    I prefer in this cases to eliminate the need of mocking with an protected method:

    public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    
        @ExceptionHandler(DataIntegrityViolationException.class)
        public ResponseEntity<Object> handle(final DataIntegrityViolationException e, final WebRequest request) {
    
            final String requestPath = getRequestUri(request);
    
            return ResponseEntity.ok().body(requestPath);
        }
    
        protected String getRequestUri(final WebRequest request) {
            return ((ServletWebRequest) request).getRequest().getRequestURI();
        }
    }
    

    And anonymous class in test:

    public class GlobalExceptionHandlerTests {
    
        private final GlobalExceptionHandler handler = new GlobalExceptionHandler() {
            @Override
            protected String getRequestUri(final org.springframework.web.context.request.WebRequest request) {
                return "http://localhost.me";
            };
        };
    
        @Test
        void test() throws Exception {
    
            final ResponseEntity<Object> handled = handler.handle(new DataIntegrityViolationException(""),
                    null);
            assertEquals("http://localhost.me", handled.getBody());
        }
    }