Java >> Java チュートリアル >  >> Tag >> Spring

Spring MockMVC 使用時に JSON レスポンスから値を抽出する方法

単純に 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);

...

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

JSON 応答から任意の一般的な値を取得する 1 つの方法は、MockMVC ライブラリの jsonPath() マッチャーを活用し、照合するように要求されたすべての値を取得するカスタム マッチャーと結合することです。

まず、カスタムマッチャー:

import org.hamcrest.BaseMatcher;

/**
 * Matcher which always returns true, and at the same time, captures the
 * actual values passed in for matching. These can later be retrieved with a
 * call to {@link #getLastMatched()} or {@link #getAllMatched()}.
 */
public static class CapturingMatcher extends BaseMatcher<Object> {

    private List<Object> matchedList = new ArrayList<>();

    @Override
    public boolean matches(Object matched) {
        matchedList.add(matched);
        return true;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("any object");
    }

    /**
     * The last value matched.
     */
    public Object getLastMatched() {
        return matchedList.get(matchedList.size() - 1);
    }

    /**
     * All the values matched, in the order they were requested for
     * matching.
     */
    public List<Object> getAllMatched() {
        return Collections.unmodifiableList(matchedList);
    }
}

ここで、カスタム マッチャーを使用して値をキャプチャし、jsonPath() マッチャーを使用してキャプチャする対象を識別します。

@Test
@WithMockUser(username = "reviewer", authorities = {ROLE_USER})
public void testGetRemediationAction() throws Exception {

    CapturingMatcher capturingMatcher = new CapturingMatcher();

    // First request a list of all the available actions
    mvc.perform(get("/api/remediation/action").accept(VERSION_1_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.content[*].remediations[*].id", hasSize(12)))
            .andExpect(jsonPath("$.content[*].remediations[*].id", capturingMatcher));

    // Grab an ID from one of the available actions
    Object idArray = capturingMatcher.getLastMatched();
    assertThat(idArray).isInstanceOf(JSONArray.class);
    JSONArray jsonIdArray = (JSONArray) idArray;
    String randomId = (String) jsonIdArray.get(new Random().nextInt(12));

    // Now retrieve the chosen action
    mvc.perform(get("/api/remediation/action/" + randomId).accept(VERSION_1_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.id", is(randomId)));
}

Java タグ