How to retrieve data directly from Spring test MvcResult json response?

13.9k Views Asked by At

I want to retrieve a value from json response in order to use in the rest of my test case, here's what I'm doing now:

MvcResult mvcResult = super.mockMvc.perform(get("url").accept(MediaType.APPLICATION_JSON).headers(basicAuthHeaders()))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$[0].id", is(6))).andReturn();

String responseAsString = mvcResult.getResponse().getContentAsString();
ObjectMapper objectMapper = new ObjectMapper(); // com.fasterxml.jackson.databind.ObjectMapper
MyResponse myResponse = objectMapper.readValue(responseAsString, MyResponse.class);

if(myResponse.getName().equals("name")) {
    //
    //
}

I'm wondering is there a more elegant way to retrieve a value directly from MvcResult as with the case of jsonPath for matching?

4

There are 4 best solutions below

0
On BEST ANSWER

I've found a more elegant way using JsonPath of Jayway:

MvcResult mvcResult = super.mockMvc.perform(get("url").accept(MediaType.APPLICATION_JSON).headers(basicAuthHeaders()))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$[0].id", is(6))).andReturn();

String response = mvcResult.getResponse().getContentAsString();
Integer id = JsonPath.parse(response).read("$[0].id");
1
On

No, unfortunately there is no way to do this more elegantly. However, you can use content().json() to do checks like .andExpect(content().json("{'name': 'name'}")) or add all required .andExpect() calls, which will be more natural for spring testing.

0
On
    public <E> E getResultList(MvcResult result, Class<E> type) {

    E listFromResponse;
    try {
        String content = result.getResponse().getContentAsString();
        ObjectMapper objectMapper = new ObjectMapper();
        listFromResponse = objectMapper.readValue(content, type);

        return listFromResponse;

    } catch (UnsupportedEncodingException | JsonProcessingException e) {
        log.error(e.getLocalizedMessage());
    }

    return (E) Optional.empty();
}

  List<SomeDto> resultList = (List<SomeDto>) getResultList(mvcResult, Iterable.class);
0
On

An alternative way is with https://github.com/lukas-krecan/JsonUnit#spring

import static net.javacrumbs.jsonunit.spring.JsonUnitResultMatchers.json;
...

this.mockMvc.perform(get("/sample").andExpect(
    json().isEqualTo("{\"result\":{\"string\":\"stringValue\", \"array\":[1, 2, 3],\"decimal\":1.00001}}")
);
this.mockMvc.perform(get("/sample").andExpect(
    json().node("result.string2").isAbsent()
);
this.mockMvc.perform(get("/sample").andExpect(
    json().node("result.array").when(Option.IGNORING_ARRAY_ORDER).isEqualTo(new int[]{3, 2, 1})
);
this.mockMvc.perform(get("/sample").andExpect(
    json().node("result.array").matches(everyItem(lessThanOrEqualTo(valueOf(4))))
);