要测试 数组的 大小:
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和Spring Test 3.2.5。
hasSize(int)javadoc
注意:您需要包括hamcrest-library依赖项,并且
import staticorg.hamcrest.Matchers.*;hasSize()才能起作用。



