2012-12-06 17 views
60

可以使用JsonPath來統計成員的數量嗎?用jsonpath計數成員?

使用spring mvc test我測試與

standaloneSetup(new FooController(fooService)).build() 
      .perform(get("/something").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) 
      .andExpect(jsonPath("$.foo").value("oof")) 
      .andExpect(jsonPath("$.bar").value("rab")); 

我想,以確保沒有其他成員在生成的JSON產生

{"foo": "oof", "bar": "rab"} 

的控制器。希望通過使用jsonPath來對它們進行計數。可能嗎?備選解決方案也是受歡迎的。

回答

126

爲了測試陣列尺寸:jsonPath("$", hasSize(4))

要計算對象的成員:jsonPath("$.*", hasSize(4))


即來測試API返回一個 4的數組項:

接受值:[1,2,3,4]

mockMvc.perform(get(API_URL)) 
     .andExpect(jsonPath("$", hasSize(4))); 

來測試API返回一個包含2個成員的對象

接受值:{"foo": "oof", "bar": "rab"}

mockMvc.perform(get(API_URL)) 
     .andExpect(jsonPath("$.*", hasSize(2))); 

我使用Hamcrest 1.3版和彈簧試驗3.2.5.RELEASE

hasSize(int) javadoc

+30

任何人想知道:全法'org.hamcrest.Matchers.hasSize',它是在'hamcrest-all'而不是'hamcrest-core' –

+1

@mattb - 如果使用Maven,不添加'hamcrest,所有'作爲依賴關係,但使用'hamcrest-library':https://code.google.com/p/hamcrest/wiki/HamcrestDistributables –

+0

如果不知道大小並想獲取它,該怎麼辦? – zygimantus

4

今天自己處理這個問題。它似乎並沒有在可用的斷言中實現。但是,有一種方法可以傳入一個org.hamcrest.Matcher對象。這樣,您可以做類似如下:

final int count = 4; // expected count 

jsonPath("$").value(new BaseMatcher() { 
    @Override 
    public boolean matches(Object obj) { 
     return obj instanceof JSONObject && ((JSONObject) obj).size() == count; 
    } 

    @Override 
    public void describeTo(Description description) { 
     // nothing for now 
    } 
}) 
0

,如果你沒有在你的classpath com.jayway.jsonassert.JsonAssert(這是我的情況)做,測試以下面的方式可以是可能的解決方法:

assertEquals(expectedLength, ((net.minidev.json.JSONArray)parsedContent.read("$")).size()); 

[注:我假定JSON的含量始終是一個數組]