How to test Exception handler with mockito without a real controller call (Spring)

I have a Controller

@RequestMapping(value = "something/{year}", method = RequestMethod.GET)
@ResponseBody
public MyObject get(@PathVariable("year") int year throws MyException {
    return myService.get(year);
}

If the year is not correct, it's gonna throw an error and this error is caught by my ErrorInterceptor class

@ExceptionHandler(value = {MyException.class})
protected ResponseEntity<Object> handleMyException(MyException ex, WebRequest request) {
    System.out.println(ex.getMessage());
    ResponseEntity<Object> res = handleExceptionInternal(ex, ex.getMessage(), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    ResponseEntity<Object> response = getMyResponse((ServletWebRequest) request, res);
    return response;
}

The method getMyResponse creates an object with customed error message (path, code error, etc.) My question is how can I test it with Mockito without making a real call of the controller. I've tested with MockMvcBuilders.standaloneSetup(controller) .setControllerAdvice(myInterceptor).build() but it's always null (I don't want to make a real call).

I also tried adding Mockito.when and Mockity.verify to fake the call but I can't get retrieve the path and stuff...

1 answer

  • answered 2022-05-04 14:53 EricSchaefer

    If you just want to know if the interceptor is returning the correct response, you could create a class which is extenting the interceptor and provides an public wrapper method for handleMyException. Then you instantiate that new class, call the wrapper and assert on the returned response.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum