Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 378
Akanksha Avatar asked Feb 10 '26 22:02

Akanksha


1 Answers

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());
    }
}
like image 96
Matthias Avatar answered Feb 12 '26 16:02

Matthias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!