Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法

这里有个往后台传json的情况
因为@RequestBody 作为参数,且需要json
请看这篇
http://www.cnblogs.com/0201zcr/p/5756642.html

引用


param:添加request的参数,如上面发送请求的时候带上了了pcode = root的参数。假如使用需要发送json数据格式的时将不能使用这种方式,可见后面被@ResponseBody注解参数的解决方法




遇到的问题

1、发送一个被@ResponseBody标识的参数,一直到400错误。 即无法发送一个json格式的数据到Controller层。

解决方法1:

复制代码
      SoftInfo softInfo = new SoftInfo();
      //设置值
     ObjectMapper mapper = new ObjectMapper();
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
        java.lang.String requestJson = ow.writeValueAsString(softInfo);
        String responseString = mockMvc.perform( post("/softs").contentType(MediaType.APPLICATION_JSON).content(requestJson)).andDo(print())
                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
复制代码
解决方法2:使用com.alibaba.fastjson.JSONObject将对象转换为Json数据

复制代码
SoftInfo softInfo = new SoftInfo();
//。。。设置值
    String requestJson = JSONObject.toJSONString(folderInfo);
        String responseString = mockMvc.perform( post("/softs").contentType(MediaType.APPLICATION_JSON).content(requestJson)).andDo(print())
                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
复制代码
  注意上面contentType需要设置成MediaType.APPLICATION_JSON,即声明是发送“application/json”格式的数据。使用content方法,将转换的json数据放到request的body中。









使用fastjson与SpringMVC实现自定义HttpMessageConverter接收和获取JSON格式的数据
http://blog.csdn.net/hloach/article/details/67632728

猜你喜欢

转载自dannyhz.iteye.com/blog/2386170