Search code examples
javajsonspringmockmvc

How to get user's id from response json


I have mockmvc test.

@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)));
    }

How can I get user id from this response to some additional variable?

For example I want something like this:

String id = jsonPath"$[0].id"; 

I know that it will not work, but I need to have user's id in variable.


Solution

  • You need to assign the result of you get call using andReturn() method. Then you can read the response content, read and assign your id to a variable. Please try :

    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");