Boh*_*ian 6 arrays size groovy jsonpath spock
鉴于json等
{"arr1" : [1,2,3], "arr2" : []}
Run Code Online (Sandbox Code Playgroud)
在哪里知道有名为arr1和arr2的数组,是否有一个jsonpath表达式用于数组的长度,它将适用于空数组和非空数组?
我使用谷歌代码的JsonPath库做了几次尝试,注意:
JsonPath.read(json, "arr1.length")
Run Code Online (Sandbox Code Playgroud)
但它给出了一个错误,说数组没有属性.
我正在寻找解析为数组长度的单个字符串路径,而不是后续调用中间体,例如
JsonPath.read(json, "arr1").length // useless to me
Run Code Online (Sandbox Code Playgroud)
表达的任何复杂程度都是可以接受的.
对于上下文,我想提供一个带路径/值对的测试套件,这对于值很有用,但是我不能用这个模式断言数组大小.
如果仅在断言时需要数组的长度,则json-path-assert可以结合使用工件JsonPath.这是一个用Groovy编写的示例:
@Grab('com.jayway.jsonpath:json-path:0.9.1')
@Grab('com.jayway.jsonpath:json-path-assert:0.9.1')
import com.jayway.jsonpath.JsonPath
import static com.jayway.jsonassert.JsonAssert.*
import static org.hamcrest.MatcherAssert.assertThat
import static org.hamcrest.Matchers.*
def json = /{ "arr1": [1,2,3], "arr2": [] }/
with(json).assertThat( "arr1", hasSize(3) )
.assertThat( "arr2", hasSize(0) )
.assertThat( "arr2", emptyCollection() )
Run Code Online (Sandbox Code Playgroud)
验证断言是否因不同大小的数组而失败.最好的部分是使用Hamcrest的Matcher API,它为灵活多变的断言打开了大门.
无法从路径表达式AFAIK获得长度.