2013-03-12 91 views
17

我目前正在爲Spring MVC項目編寫一些單元測試。 由於返回的媒體類型是JSON,我嘗試使用jsonPath來檢查是否返回了正確的值。SpringMVC/mockMVC/jsonpath比較字符串列表

我遇到的麻煩是驗證字符串列表是否包含正確的(並且只有正確的)值。

我的計劃是:

  1. 檢查列表中有正確的長度
  2. 對於數字應返回的每個元素,檢查它是否在列表中的

可悲的是,沒有任何的這些東西似乎工作。

這裏是我的代碼的相關部分:

Collection<AuthorityRole> correctRoles = magicDataSource.getRoles(); 

ResultActions actions = this.mockMvc.perform(get("/accounts/current/roles").accept(MediaType.APPLICATION_JSON)) 
.andExpect(status().isOk()) // works 
.andExpect(jsonPath("$.data.roles").isArray()) // works 
.andExpect(jsonPath("$.data.roles.length").value(correctRoles.size())); // doesn't work 

for (AuthorityRole role : correctRoles) // doesn't work 
    actions.andExpect(jsonPath("$.data.roles[?(@=='%s')]", role.toString()).exists()); 

只有前兩個 「預期」(ISOK & IsArray的)都在工作。其他的(長度和內容)我可以扭曲和轉動,但我想,他們沒有給我任何有用的結果。

有什麼建議嗎? )代替

.andExpect(jsonPath("$.data.roles.length").value(correctRoles.size())); 

回答

42

1嘗試

.andExpect((jsonPath("$.data.roles", Matchers.hasSize(size)))); 

2)代替

for (AuthorityRole role : correctRoles) // doesn't work 
    actions.andExpect(jsonPath("$.data.roles[?(@=='%s')]", role.toString()).exists()); 

嘗試

actions.andExpect((jsonPath("$.data.roles", Matchers.containsInAnyOrder("role1", "role2", "role3")))); 

請記住,你必須添加hamcrest-library。

+0

非常感謝您!這非常有幫助! – 2013-03-15 17:51:52

+0

如果它有幫助,你可以標記我的答案爲接受:) – chaldaean 2013-03-16 11:54:42

+0

@chaldaean你用什麼hamcrest圖書館?在我所知道的那個中,hamcrest-all-1.1,類org.hamcrest.Matchers不包含hasSize和containsInAnyOrder方法。 – 2013-06-05 07:23:01

0

這裏是我最終使用:

.andExpect(jsonPath('$.data.roles').value(Matchers.hasSize(size)))

.andExpect(jsonPath('$.data.roles').value(Matchers.containsInAnyOrder("role1", "role2", "role3")))