用jsonpath计数成员? [英] count members with jsonpath?

查看:399
本文介绍了用jsonpath计数成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用JsonPath计算成员数量?

Is it possible to count the number of members using JsonPath?

使用 spring mvc测试我正在测试生成控制器

Using spring mvc test I'm testing a controller that generates

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

使用

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中没有其他成员.希望通过使用jsonPath计数它们.是否有可能?也欢迎使用其他解决方案.

I'd like to make sure that no other members are present in the generated json. Hopefully by counting them using jsonPath. Is it possible? Alternate solutions are welcome too.

推荐答案

要测试数组的大小:jsonPath("$", hasSize(4))

要计算对象的成员:jsonPath("$.*", hasSize(4))

即测试API是否返回由4个项目组成的数组:

I.e. to test that API returns an array of 4 items:

接受值:[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.RELEASE


I'm using Hamcrest version 1.3 and Spring Test 3.2.5.RELEASE

hasSize(int)javadoc

注意: 您需要包括hamcrest-library依赖项和import static org.hamcrest.Matchers.*;,以使hasSize()起作用.

Note: You need to include hamcrest-library dependency and import static org.hamcrest.Matchers.*; for hasSize() to work.

这篇关于用jsonpath计数成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆