[英]How to get json response from inside the page from Webview(I get a response with user-agent)?
[英]How to get user's id from response json
我有模擬測試。
@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()
方法分配get調用的結果。 然后,您可以讀取響應內容,讀取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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.