使用Spring MockMVC时如何从JSON响应中提取价值

我有一个接受 POST 请求的终结点。我想从 JSON 响应中获取新创建的实体的 ID。

下面是我尝试执行此操作的代码的一部分。

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

如果我获得该 ID,我将查询数据库中新创建的实体,并执行一些断言,如下所示:

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

答案 1

您只需在结果对象上使用:JsonPath.read

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

...

答案 2

我已经设法使用Spring MockMVC结果处理程序解决了我的问题。我创建了一个测试实用程序,将JSON字符串转换回对象,从而允许我获取ID。

转换实用程序:

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

单元测试:

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

推荐