如何对spring mvc控制器发送的ResponseBody或ResponseEntity进行单元测试? [英] How to unit test a ResponseBody or ResponseEntity sent by a spring mvc Controller?

查看:125
本文介绍了如何对spring mvc控制器发送的ResponseBody或ResponseEntity进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我进行junit测试时,我会做类似的测试spring mvc控制器:

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);

其中控制器测试如下:

@RequestMapping(value = "{id}/modify")
public String content(ModelMap model, @PathVariable("id") Project object) {

但是我找不到如何获得 ResponseBody 请求的答案处理程序定义如下:

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;
    }


推荐答案

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

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

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

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

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.

这篇关于如何对spring mvc控制器发送的ResponseBody或ResponseEntity进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆