美文网首页SpringBoot云课堂我爱编程
基于JUnit和Servlet的Mock对象测试返回的json和

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

作者: seymour1996 | 来源:发表于2018-01-15 16:34 被阅读13次

验证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

相关文章

网友评论

    本文标题:基于JUnit和Servlet的Mock对象测试返回的json和

    本文链接:https://www.haomeiwen.com/subject/dvldoxtx.html