问题描述
我正在使用Spring的"spring-test-mvc"库来测试Web控制器.我有一个非常简单的控制器,它返回一个JSON数组.然后在我的测试中,我有:
I am using Spring's "spring-test-mvc" library to test web controllers. I have a very simple controller that returns a JSON array. Then in my test I have:
@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
要快速检查我实际得到的内容,我进行了以下测试:
To quickly check what I actually get I ran the below test:
@Test
public void shouldPrintResults() throws Exception {
mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON))
.andDo(print());
}
它在MockHttpServletResponse
我不确定为什么jsonPath
在JSON数组中看不到fName
.
I'm not sure why jsonPath
is not able to see fName
in the JSON array.
推荐答案
您的json响应主体是什么样的?您可以通过执行.andDo(print())
What does your json response body look like? You can see it by doing an .andDo(print())
您可能想尝试jsonPath("$.fName")
.
这是假设您的json响应是:{"fName":"first name"}
This is assuming that your json response is:{"fName":"first name"}
如果您的响应是一个数组,那么您需要jsonPath("$[0].fName")
来进行响应,例如:[{"fName":"first name"},{"fName":"first name #2"}]
If your response is an array then you need jsonPath("$[0].fName")
for a response like:[{"fName":"first name"},{"fName":"first name #2"}]
您可以在以下位置看到更多示例: http://goessner.net/articles/JsonPath/
You can see more examples at: http://goessner.net/articles/JsonPath/
这篇关于使用spring-test-mvc jsonpath进行测试将返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!