如何使用Mockito测试异常处理程序,而没有真实的控制器调用(春季)
我有一个控制器,
@RequestMapping(value = "something/{year}", method = RequestMethod.GET)
@ResponseBody
public MyObject get(@PathVariable("year") int year throws MyException {
return myService.get(year);
}
如果一年不正确,它将丢弃错误,并且此错误是由我的ErrorInterceptor类捕获的,
@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;
}
方法GetMyResponse创建了一个具有自定义错误消息(路径,代码错误等)的对象。 我的问题是,如何在不真正呼叫控制器的情况下使用Mockito对其进行测试。 我已经使用MockMvcBuilders.standalonesetup(Controller).setControllerAdvice(myInterceptor).build()进行了测试。
我还尝试添加Mockito。和Mockity。
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只想知道拦截器是否正在返回正确的响应,则可以创建一个正在限制拦截器的类,并为
handlemyException
提供公共包装方法。然后,您实例化了新课程,请致电包装器并断言返回的响应。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.