Java 使用jsonpath计算成员数?
是否可以使用JsonPath计算成员数 我正在测试一个生成Java 使用jsonpath计算成员数?,java,spring,testing,jsonpath,spring-test-mvc,Java,Spring,Testing,Jsonpath,Spring Test Mvc,是否可以使用JsonPath计算成员数 我正在测试一个生成 {"foo": "oof", "bar": "rab"} 与 我希望确保生成的json中没有其他成员。希望通过使用jsonPath计算它们。可能吗?也欢迎其他解决方案。我今天一直在处理这个问题。这似乎不是在可用断言中实现的。但是,有一种方法可以传入org.hamcrest.Matcher对象。这样,您可以执行以下操作: final int count = 4; // expected count jsonPath("$").valu
{"foo": "oof", "bar": "rab"}
与
我希望确保生成的json中没有其他成员。希望通过使用jsonPath计算它们。可能吗?也欢迎其他解决方案。我今天一直在处理这个问题。这似乎不是在可用断言中实现的。但是,有一种方法可以传入
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
}
})
要测试数组的大小:
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”}
我使用的是Hamcrest 1.3版和Spring Test 3.2.5.0版本 注:
您需要包括hamcrest库依赖项和导入静态org.hamcrest.Matchers.*代码>让hasSize()工作。如果类路径上没有
com.jayway.jsonassert.jsonassert
(我就是这样),那么以以下方式进行测试可能是一种可行的解决方法:
assertEquals(expectedLength, ((net.minidev.json.JSONArray)parsedContent.read("$")).size());
[注意:我假设json的内容始终是一个数组]我们可以使用类似size()
或length()
,如下所示:
@Test
public void givenJson_whenGetLengthWithJsonPath_thenGetLength() {
String jsonString = "{'username':'jhon.user','email':'jhon@company.com','age':'28'}";
int length = JsonPath
.parse(jsonString)
.read("$.length()");
assertThat(length).isEqualTo(3);
}
或者简单地解析到net.minidev.json.JSONObject
并获取大小:
@Test
public void givenJson_whenParseObject_thenGetSize() {
String jsonString = "{'username':'jhon.user','email':'jhon@company.com','age':'28'}";
JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString);
assertThat(jsonObject)
.size()
.isEqualTo(3);
}
事实上,第二种方法看起来比第一种方法表现得更好。我进行了JMH性能测试,得到了以下结果:
| Benchmark | Mode | Cnt | Score | Error | Units |
|-------------------------------------------------|-------|-----|-------------|--------------|-------|
| JsonPathBenchmark.benchmarkJSONObjectParse | thrpt | 5 | 3241471.044 | ±1718855.506 | ops/s |
| JsonPathBenchmark.benchmarkJsonPathObjectLength | thrpt | 5 | 1680492.243 | ±132492.697 | ops/s |
可以找到示例代码。您也可以使用jsonpath中的方法,因此
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.*", hasSize(2)));
你能行
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.length()", is(2)));
@mattb-如果使用Maven,不要将
hamcrest all
作为依赖项添加,而是使用hamcrest library
:如果不知道大小并想要得到它怎么办?@menuka ishan-我认为它不被弃用,根据:javadoc@zygimantus必须计算对象/数组上所有字段的大小,从源代码或web浏览器开发人员工具检查响应。对于kotlin,您可能需要添加如下类型参数:.andExpect(jsonPath(“$”,hasSize(4))
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.*", hasSize(2)));
mockMvc.perform(get(API_URL))
.andExpect(jsonPath("$.length()", is(2)));