基于JUnit和Servlet的Mock对象测试返回的json和xml数据

验证json数据

1. 使用jsponPath解析json数据对属性逐项验证

@Test
    public void testDemoRestController() throws Exception {
        mockMvc.perform(get("/rest/getjson?id=123456&name=aaa"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.id").value(123457))
                .andExpect(jsonPath("$.name").value("aaayy"));
      }
使用这种方法要添加jsonPth依赖
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>

2. 使用content().json验证一整串的json数据

@Test
    public void testDemoRestController() throws Exception {
        mockMvc.perform(get("/rest/getjson?id=123456&name=aaa"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(content().json("{\"id\":123457,\"name\":\"aaayy\"}"));
      }
使用这种方法要添加jsonassert依赖
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.5.0</version>
<scope>test</scope>
</dependency>

验证xml数据

1. 使用xpath解析xml数据对属性逐项验证

@Test
    public void testDemoRestController() throws Exception {
        mockMvc.perform(get("/rest/getxml?id=123456&name=aaa"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/xml;charset=UTF-8"))
                .andExpect(xpath("/DemoObj/id").string("123457"))
                .andExpect(xpath("/DemoObj/name").string("aaayy"));
      }

2. 使用content().xml验证一整串的xml数据

@Test
    public void testDemoRestController() throws Exception {
        mockMvc.perform(get("/rest/getxml?id=123456&name=aaa"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/xml;charset=UTF-8"))
                .andExpect(content().xml("<DemoObj xmlns=\"\"><id>123457</id><name>aaayy</name></DemoObj>"));
      }
使用这种方法要添加xmlunit依赖
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
JSONPath和Xpath语法:

JSONPath和XPath语法

具体语法及例子可参考:http://blog.csdn.net/luxideyao/article/details/77802389

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,908评论 18 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,229评论 4 61
  • 那些养肉的蓝孩子,告诉我,你为什么要养肉肉? 那些养肉的蓝孩子,告诉我,你为什么把肉肉养的这么好? 那些养肉的蓝孩...
    知丫爱多肉阅读 533评论 0 1
  • 在我们村,家家户户的房屋都是挨着山脚而建的。每次我打开家中的后门,都可以看到屋后的那座大山,山上满是草蕨树木,偶有...
    曾晨风阅读 327评论 0 0