如何使用mockMvc检查响应体中的JSON [英] How to check JSON in response body with mockMvc

查看:2249
本文介绍了如何使用mockMvc检查响应体中的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的控制器内的方法,由 @Controller注释

This is my method inside my controller which is annotated by @Controller

@RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JSONObject getServerAlertFilters(@PathVariable String serverName) {
        JSONObject json = new JSONObject();
        List<FilterVO> filteredAlerts = alertFilterService.getAlertFilters(serverName, "");
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(filteredAlerts);
        json.put(SelfServiceConstants.DATA, jsonArray);
        return json;
    }

我期待 {data:[{ useRegEx:false,hosts:v2v2v2}]} 作为我的json。

I am expecting {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} as my json.

这是我的JUnit测试:

And this is my JUnit test:

@Test
    public final void testAlertFilterView() {       
        try {           
            MvcResult result = this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").session(session)
                    .accept("application/json"))
                    .andDo(print()).andReturn();
            String content = result.getResponse().getContentAsString();
            LOG.info(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

以下是控制台输出:

MockHttpServletResponse:
              Status = 406
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

甚至 result.getResponse()。getContentAsString()是一个空字符串。

有人可以建议如何在我的JUnit测试方法中获取我的JSON,以便我可以完成我的测试用例。

Can someone please suggest how to get my JSON in my JUnit test method so that I can complete my test case.

推荐答案

406 Not Acceptable 状态代码表示Spring无法将对象转换为json。您可以让您的控制器方法返回一个字符串并执行返回json.toString(); 或配置您自己的 HandlerMethodReturnValueHandler 。请查看类似的问题使用SpringMVC中的@ResponseBody返回JsonObject

The 406 Not Acceptable status code means that Spring couldn't convert the object to json. You can either make your controller method return a String and do return json.toString(); or configure your own HandlerMethodReturnValueHandler. Check this similar question Returning JsonObject using @ResponseBody in SpringMVC

这篇关于如何使用mockMvc检查响应体中的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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