java - 如何从响应 json 中获取用户的 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。
解决方案
您需要使用andReturn()
方法分配调用的结果。然后您可以读取响应内容,读取您的 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");
推荐阅读
- java - 尝试将 Spring MVC 集成到现有的 Jersey API 中,每次 404
- angular - 如何自定义 PrimeNG TurboTable 分页器?
- python - PYQT:如何将自定义信号从主窗口(父)发送到子窗口?
- android - 从列表视图中删除项目 onlongclick
- javascript - 如何在vue js中修复谷歌地图中心位置
- google-apps-script - Google Apps 脚本 - 表格 - 包含 INCLUDES 的 IF 语句
- javascript - Javascript数字比较不正确
- gradle - 无法使用 gradle 从 nexus 下载 ojdbc 特定 jar
- r - 如何使用 ggplot 自定义 plotCounts (DESeq2) 输出?
- delphi - tDBLookupComboBox 显示 (MEMO)