Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 378
Mohamed Elsayed Avatar asked Nov 26 '18 18:11

Mohamed Elsayed


People also ask

What is MvcResult?

public interface MvcResult. Provides access to the result of an executed request.


Video Answer


3 Answers

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");
like image 86
Mohamed Elsayed Avatar answered Oct 18 '22 01:10

Mohamed Elsayed


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.

like image 23
Danylo Rosiichuk Avatar answered Oct 18 '22 03:10

Danylo Rosiichuk


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))))
);
like image 26
gavenkoa Avatar answered Oct 18 '22 02:10

gavenkoa