首页 > 解决方案 > 如何从响应 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。

标签: javajsonspringmockmvc

解决方案


您需要使用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");

推荐阅读