jsf*_*jsf 3 spring spring-test mockito jsonpath spring-test-mvc
我正在使用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());
}
Run Code Online (Sandbox Code Playgroud)
以上测试返回:
java.lang.AssertionError: No value for JSON path: fName
Run Code Online (Sandbox Code Playgroud)
为了快速检查我实际得到的内容,我运行了以下测试:
@Test
public void shouldPrintResults() throws Exception {
mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON))
.andDo(print());
}
Run Code Online (Sandbox Code Playgroud)
它返回正文中的正确JSON数组 MockHttpServletResponse
我不确定为什么jsonPath
无法fName
在JSON数组中看到.
Bre*_*son 10
如果将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>
Run Code Online (Sandbox Code Playgroud)
您可能还需要hamcrest库来使用jsonPath("$.test").value("test")
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
Bre*_*son 10
你的json响应体看起来像什么?你可以通过做一个看到它.andDo(print())
你可能想尝试一下jsonPath("$.fName")
.
这假设你的json响应是:
{"fName":"first name"}
如果您的响应是一个数组,那么您需要jsonPath("$[0].fName")
一个响应,如:
[{"fName":"first name"},{"fName":"first name #2"}]
您可以在以下网址查看更多示例:http://goessner.net/articles/JsonPath/
归档时间: |
|
查看次数: |
11093 次 |
最近记录: |