2017-02-16 72 views
1

我寫我的REST API控制器測試,我需要從返回JSON對象檢查UUID值,請參閱該測試方法:MockMvc JsonPath結果匹配不匹配的單值

@Test 
public void findById() throws Exception { 

    final String uuidString = "6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1"; 
    final UUID id = UUID.fromString(uuidString); 
    final Envelope envelope = createEnvelope(id); 

    when(envelopeService.findOne(id, currentUser)).thenReturn(Optional.of(envelope)); 
    when(utilService.getLoggedInUser()).thenReturn(currentUser); 

    mockMvc.perform(get("/api/envelopes/{id}", uuidString)). 
      andExpect(status().isOk()).andExpect(content().contentType(Util.APPLICATION_JSON_UTF8)) 
      .andExpect(jsonPath("$..id", is(uuidString))); 

    verify(envelopeService, times(1)).findOne(id, currentUser); 
    //verifyNoMoreInteractions(envelopeService); 

} 

但測試產生這個錯誤:

Expected: is "6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1" 
     but: was <["6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1"]> 
     at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20) 
     at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:74) 
     at org.springframework.test.web.servlet.result.JsonPathResultMatchers$1.match(JsonPathResultMatchers.java:86) 
     at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171) 

似乎ID 6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1返回正確,但在序列化到不同的結構。

我的代碼有什麼問題?

+0

您可以發佈impl。的api .. – Jaiwo99

+0

這與具體實施無關。我需要知道如何檢查返回的UUID值等於我的值。 – Artegon

回答

0

正如我所看到的,jsonPath變量是一個對象數組,而不是單個字符串。

您應該使用$[0]讓你的情況第一和唯一的元素,這就是UUID:

mockMvc.perform(get("/api/envelopes/{id}", uuidString)). 
      andExpect(status().isOk()) 
      .andExpect(content().contentType(Util.APPLICATION_JSON_UTF8)) 
      .andExpect(jsonPath("$[0]", is(uuidString))); 
0

的原因是你的jsonpath聲明是錯誤的

"6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1" <--- String 
<["6c2b1c8a-3c29-4160-98b0-b8eaea7ea4d1"]> <--- Array 

,你不應該使用$..id,它給你一個陣列回來。在此處簽出文檔https://github.com/jayway/JsonPath