3

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

Akanksha
  • 181
  • 3
  • 8
  • 1
    Hi, what you are trying to do. you want to do junit test with spring boot. – Ranjith Bokkala Feb 13 '20 at 16:21
  • That's correct - you definitely want to familiarize yourself with JUnit (preferably JUnit 5) and Mockito. Here's a link regarding your specific question: https://www.baeldung.com/mockito-exceptions – FoggyDay Feb 13 '20 at 16:29
  • 1
    You don't want to mock that at all; in a normal unit test setting where you'd use mocks, this won't even be available. In a `@SpringBootTest` or something where the context is loaded up, you'd just need to trigger the exception to verify the handler was activated. – daniu Feb 13 '20 at 16:29

1 Answers1

6

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());
    }
}
Matthias
  • 1,378
  • 10
  • 23