2016-10-04 81 views
1

我寫了Spring控制器Junits。 我使用JsonPath使用["$..id"]從JSON中獲取所有ID。用Hamcrest Matchers檢查JsonPath的輸出

我有以下的測試方法:

mockMvc.perform(get(baseURL + "/{Id}/info", ID).session(session)) 
    .andExpect(status().isOk()) // Success 
    .andExpect(jsonPath("$..id").isArray()) // Success 
    .andExpect(jsonPath("$..id", Matchers.arrayContainingInAnyOrder(ar))) // Failed 
    .andExpect(jsonPath("$", Matchers.hasSize(ar.size()))); // Success 

以下是我傳遞的數據: -

List<String> ar = new ArrayList<String>(); 
ar.add("ID1"); 
ar.add("ID2"); 
ar.add("ID3"); 
ar.add("ID4"); 
ar.add("ID5"); 

我失敗消息爲: -

Expected: [<[ID1,ID2,ID3,ID4,ID5]>] in any order 
    but: was a net.minidev.json.JSONArray (<["ID1","ID2","ID3","ID4","ID5"]>) 

問題是:如何處理JSONArray與org.hamcrest.Matchers;有沒有簡單的方法可以使用jsonPath

設置: - hamcrest-all-1.3 jarjson-path-0.9.0.jarspring-test-4.0.9.jar

回答

2

JSONArray不是一個數組而是一個ArrayList(即,java.util.List)。

因此,你不應該使用Matchers.arrayContainingInAnyOrder(...)而是Matchers.containsInAnyOrder(...)

0

遇到同樣的問題,通過下面

Matchers.containsInAnyOrder(new String[]{"ID1","ID2","ID3","ID4","ID5"}) 
0

解決您應該使用:

(jsonPath("$..id", hasItems(id1,id2))