如何从响应中获取用户 ID json
How to get user's id from response json
我有 mockmvc 测试。
@Test
public void findAllUsers() throws Exception {
mockMvc.perform(MockMvcRequestBuilders
.get("http://localhost:8081/user/get")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].name", is("Ann")))
.andExpect(jsonPath("$[0].products", hasSize(2)))
.andExpect(jsonPath("$[1].name", is("John")))
.andExpect(jsonPath("$[1].products", hasSize(1)));
}
如何从这个对某些附加变量的响应中获取用户 ID?
例如我想要这样的东西:
String id = jsonPath"$[0].id";
我知道这行不通,但我需要在变量中包含用户 ID。
$.id
将用于获取 ID 或获取用户的 ID $.*.id
或 $[*].id
将起作用。
您需要使用 andReturn()
方法分配 get call 的结果。然后你可以读取响应内容,读取并将你的id分配给一个变量。请尝试:
MvcResult result = mockMvc.perform(MockMvcRequestBuilders
.get("http://localhost:8081/user/get")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].name", is("Ann")))
.andExpect(jsonPath("$[0].products", hasSize(2)))
.andExpect(jsonPath("$[1].name", is("John")))
.andExpect(jsonPath("$[1].products", hasSize(1)))
.andReturn();
String content = result.getResponse().getContentAsString();
String id = JsonPath.read(content, "[0].id");
我有 mockmvc 测试。
@Test
public void findAllUsers() throws Exception {
mockMvc.perform(MockMvcRequestBuilders
.get("http://localhost:8081/user/get")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].name", is("Ann")))
.andExpect(jsonPath("$[0].products", hasSize(2)))
.andExpect(jsonPath("$[1].name", is("John")))
.andExpect(jsonPath("$[1].products", hasSize(1)));
}
如何从这个对某些附加变量的响应中获取用户 ID?
例如我想要这样的东西:
String id = jsonPath"$[0].id";
我知道这行不通,但我需要在变量中包含用户 ID。
$.id
将用于获取 ID 或获取用户的 ID $.*.id
或 $[*].id
将起作用。
您需要使用 andReturn()
方法分配 get call 的结果。然后你可以读取响应内容,读取并将你的id分配给一个变量。请尝试:
MvcResult result = mockMvc.perform(MockMvcRequestBuilders
.get("http://localhost:8081/user/get")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].name", is("Ann")))
.andExpect(jsonPath("$[0].products", hasSize(2)))
.andExpect(jsonPath("$[1].name", is("John")))
.andExpect(jsonPath("$[1].products", hasSize(1)))
.andReturn();
String content = result.getResponse().getContentAsString();
String id = JsonPath.read(content, "[0].id");