How to extract value from JSON response when using Spring MockMVC

Chol Nhial picture Chol Nhial · Dec 12, 2017 · Viewed 13.8k times · Source

I have an endpoint that accepts a POST request. I want to get the ID of the newly created entity from the JSON response.

Below is a segment of my code where I'm attempting to do that.

mockMvc.perform(post("/api/tracker/jobs/work")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(workRequest)))
        .andExpect(status().isCreated());

If I get that ID I'll query the database for the newly created entity and do some assertions like below:

Work work = work service.findWorkById(id);

assertThat(work.getJobItem().getJobItemName()).isEqualTo(workRequest.getJobItem().getJobItemName());
assertThat(work.getJobItem().getQuantities()).hasSize(workRequest.getQuantities().size());
assertThat(work.getJobItem().getQuantityPools()).hasSize(workRequest.getQuantities().size());

Answer

Martin Busley picture Martin Busley · Aug 26, 2019

You can simply use JsonPath.read on the result object:

MvcResult result = mockMvc.perform(post("/api/tracker/jobs/work")
    .contentType(TestUtil.APPLICATION_JSON_UTF8)
    .content(TestUtil.convertObjectToJsonBytes(workRequest)))
    .andExpect(status().isCreated())
    .andReturn();    

String id = JsonPath.read(result.getResponse().getContentAsString(), "$.id")

Work work = workService.findWorkById(id);

...