java 如何对 spring mvc 控制器发送的 ResponseBody 或 ResponseEntity 进行单元测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5394002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:54:51  来源:igfitidea点击:

How to unit test a ResponseBody or ResponseEntity sent by a spring mvc Controller?

javaunit-testingspring-mvcjunit

提问by Nico

When I do junit tests, I do something like this to test spring mvc controllers :

当我做 junit 测试时,我会做这样的事情来测试 spring mvc 控制器:

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 ResponseBodyanswer of request handlers defined like this :

但我没有找到如何获得这样ResponseBody定义的请求处理程序的答案:

@RequestMapping("/management/search")
public @ResponseBody ArrayList<SearchData> search(@RequestParam("q")) {
        ....
                ....
        ArrayList<SearchData> datas = ....;

        return datas;
    }

采纳答案by skaffman

Your unit test only needs to verify the contents of the return value of the method:

你的单元测试只需要验证方法返回值的内容:

ArrayList<SearchData> results = controller.search("value");
assertThat(results, ...)

The @ResponseBodyannotation 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.

@ResponseBody注释是不相关的。这是带注释的控制器的一大好处 - 您的单元测试可以专注于业务逻辑,而不是框架机制。使用预注释控制器,您的测试代码的一半用于构建模拟请求、响应和类似的相关联的 gubbins。这是一种干扰。

Testing that your code's annotations integrate properly with the framework is the job of integration and/or functional tests.

测试您的代码的注释是否与框架正确集成是集成和/或功能测试的工作。