验证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语法:
具体语法及例子可参考:http://blog.csdn.net/luxideyao/article/details/77802389