2014-08-29 66 views
3

我正在爲使用MockMvc和JsonPath的Spring HATEOAS後端編寫單元測試。 爲了測試包含在我做類似的響應鏈接:Spring HATEOAS/MockMvc/JsonPath最佳實踐

@Test 
public void testListEmpty() throws Exception { 
    mockMvc.perform(get("/rest/customers")) 
      .andExpect(status().isOk()) 
      .andExpect(content().contentType(MediaType.APPLICATION_JSON)) 
      .andExpect(jsonPath("$.links", hasSize(1))) // make sure links only contains self link 
      .andExpect(jsonPath("$.links[?(@.rel=='self')]", hasSize(1))) // make sure the self link exists 1 time 
      .andExpect(jsonPath("$.links[?(@.rel=='self')].href", contains("http://localhost/rest/customers{?page,size,sort}"))) // test self link is correct 
      .andExpect(jsonPath("$.links[?(@.rel=='self')][0].href", is("http://localhost/rest/customers{?page,size,sort}"))) // alternative to test self link is correct 
      .andExpect(jsonPath("$.content", hasSize(0))); // make sure no content elements exists 
} 

但是我不知道是否有我應該使用,使一些最佳做法,很容易爲自己喜歡的:

  • 測試鏈接包含http://localhost感覺不對。我可以使用一些Spring MovkMvc助手來確定主機嗎?
  • 使用JsonPath,很難測試一個數組是否包含其中2個屬性具有特定值的元素。 就像這個數組應該包含一個具有特定值的自鏈接。 有沒有更好的方法來測試,然後上面 當測試錯誤消息字段的驗證錯誤時,這也會發揮作用。

我已經看到類似的技術在以下一些博客文章:

.andExpect(jsonPath("$.fieldErrors[*].path", containsInAnyOrder("title", "description"))) 
.andExpect(jsonPath("$.fieldErrors[*].message", containsInAnyOrder(
    "The maximum length of the description is 500 characters.", 
    "The maximum length of the title is 100 characters."))); 

但這並不是在所有的標題保證了特定的錯誤信息。 也可能是標題錯誤地顯示了「描述的最大長度爲500個字符」。但測試會成功。

回答