我正在使用spring的"spring- test -mvc“库来测试web控制器。我有一个非常简单的控制器,它返回一个JSON数组。然后在我的测试中,我有:
@Test
public void shouldGetAllUsersAsJson() throws Exception {
mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON))
.andExpect(content().mimeType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("fName").exists());
}上面的测试返回:
java.lang.AssertionError: No value for JSON path: fName为了快速检查我实际得到了什么,我运行了以下测试:
@Test
public void shouldPrintResults() throws Exception {
mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON))
.andDo(print());
}并在MockHttpServletResponse的主体中返回正确的JSON数组。
我不确定为什么jsonPath不能在JSON数组中看到fName。
发布于 2012-11-13 23:57:59
如果您将json路径依赖项添加到maven,或者将jar添加到库中,那么它将正常工作。我认为在最新的Spring3.2.0 RC1版本中,Spring并没有包含jsonPath依赖。我猜Spring-Test-MVC独立项目也是如此。
下面是Maven的依赖关系:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>您可能还需要hamcrest库才能使用jsonPath(“$.test”)测试(“.value”)
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>发布于 2012-11-14 05:52:31
你的json响应体是什么样子的?您可以通过执行.andDo(print())来查看它
你可能想试试jsonPath("$.fName")。
这里假设您的json响应是:{"fName":"first name"}
如果您的响应是一个数组,那么您需要像[{"fName":"first name"},{"fName":"first name #2"}]这样的响应的jsonPath("$[0].fName")
你可以在http://goessner.net/articles/JsonPath/上看到更多的例子
https://stackoverflow.com/questions/13362372
复制相似问题