我正在使用 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());
}
它在正文中返回正确的 JSON 数组MockHttpServletResponse
我不知道为什么jsonPath
看不见fName
在 JSON 数组中。
如果你将 json 路径依赖添加到 maven,或者将 jar 添加到你的 lib,那么它就会工作。我认为 Spring 在最新的 Spring 3.2.0 RC1 版本中不包含 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("test")
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)