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?
public interface MvcResult. Provides access to the result of an executed request.
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");
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.
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))))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With