2017-12-11 19 views
0

私はPOSTリクエストを受け付けるエンドポイントを持っています。新しく作成したエンティティのIDをJSONレスポンスから取得したいSpring MockMVCを使用しているときのJSON応答から値を抽出する方法

以下は私のコードのセグメントです。私はそれをやろうとしています。

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

私は春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()); 
} 
関連する問題