如何对 spring mvc 控制器发送的 ResponseBody 或 ResponseEntity 进行单元测试?
当我进行 junit 测试时,我会执行类似的操作来测试 spring mvc 控制器:
request.setRequestURI("/projects/"+idProject+"/modify");
ModelAndView mv = handlerAdapter.handle(request, response, controller);
测试的控制器如下所示:
@RequestMapping(value = "{id}/modify")
public String content(ModelMap model, @PathVariable("id") Project object) {
但我不知道如何获取如下定义的请求处理程序的 ResponseBody 答案:
@RequestMapping("/management/search")
public @ResponseBody ArrayList<SearchData> search(@RequestParam("q")) {
....
....
ArrayList<SearchData> datas = ....;
return datas;
}
When I do junit tests, I do something like this to test spring mvc controllers :
request.setRequestURI("/projects/"+idProject+"/modify");
ModelAndView mv = handlerAdapter.handle(request, response, controller);
where controller tested is like :
@RequestMapping(value = "{id}/modify")
public String content(ModelMap model, @PathVariable("id") Project object) {
But I don't find how to get the ResponseBody
answer of request handlers defined like this :
@RequestMapping("/management/search")
public @ResponseBody ArrayList<SearchData> search(@RequestParam("q")) {
....
....
ArrayList<SearchData> datas = ....;
return datas;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的单元测试只需要验证方法的返回值的内容:
@ResponseBody
注释是无关紧要的。这是带注释的控制器的一大好处 - 您的单元测试可以专注于业务逻辑,而不是框架机制。使用预注释控制器,一半的测试代码用于构建模拟请求、响应和相关的 gubbin。这是一种干扰。测试代码的注释是否与框架正确集成是集成和/或功能测试的工作。
Your unit test only needs to verify the contents of the return value of the method:
The
@ResponseBody
annotation is irrelevant. This is one of the big benefits of annotated controllers - your unit tests can focus on the business logic, not the framework mechanics. With pre-annotation controllers, half of your test code is spent constructing mock requests, responses, and associated gubbins like that. It's a distraction.Testing that your code's annotations integrate properly with the framework is the job of integration and/or functional tests.