Search code examples
javaspringspring-bootintegration-testingmockmvc

How to extract value from JSON response when using Spring MockMVC


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

Solution

  • I have managed to solve my problem using Spring MockMVC result handler. I created a testing utility to convert the JSON string back to an object and so allowing me to get the ID.

    Conversion Utility:

     public static <T>  Object convertJSONStringToObject(String json, Class<T> objectClass) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    
        JavaTimeModule module = new JavaTimeModule();
        mapper.registerModule(module);
        return mapper.readValue(json, objectClass);
    }
    

    Unit Test:

     @Test
    @Transactional
    public void createNewWorkWorkWhenCreatedJobItemAndQuantitiesPoolShouldBeCreated() throws Exception {
    
        mockMvc.perform(post("/api/tracker/jobs/work")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(workRequest)))
            .andExpect(status().isCreated())
            .andDo(mvcResult -> {
                String json = mvcResult.getResponse().getContentAsString();
                workRequestResponse = (WorkRequestResponse) TestUtil.convertJSONStringToObject(json, WorkRequestResponse.class);
            });
    
        Work work = workService.findWorkById(workRequestResponse.getWorkId());
    
        assertThat(work.getJobItem().getJobItemName()).isEqualTo(workRequest.getJobItem().getJobItemName());
        assertThat(work.getJobItem().getQuantities()).hasSize(workRequest.getQuantities().size());
        assertThat(work.getJobItem().getQuantityPools()).hasSize(workRequest.getQuantities().size());
    }