如何使用Mockito测试异常处理程序,而没有真实的控制器调用(春季)

发布于 2025-01-26 01:40:27 字数 1052 浏览 5 评论 0原文

我有一个控制器,

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

还在原地等你 2025-02-02 01:40:27

如果您只想知道拦截器是否正在返回正确的响应,则可以创建一个正在限制拦截器的类,并为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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文