基于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依赖

com.jayway.jsonpath
json-path
2.0.0
test

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依赖

org.skyscreamer
jsonassert
1.5.0
test

验证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("123457aaayy"));
      }
使用这种方法要添加xmlunit依赖

xmlunit
xmlunit
1.3
test

JSONPath和Xpath语法:

JSONPath和XPath语法

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

你可能感兴趣的:(基于JUnit和Servlet的Mock对象测试返回的json和xml数据)