为什么 'each' 循环在数组为空时不 运行

Why the 'each' loop does not run when the array is empty

我有一个脚本断言,它应该只是抽查响应中的每一项,并检查每一项都是正确的数据类型。 我注意到当响应为空时,每个循环似乎都没有 运行,因此断言在它不应该通过的地方通过。

规则ID是响应中的一个字段,但是当请求条件不匹配任何交易时,它将return一个空数组。

这是每个循环的正确行为吗?如果是这样,最好的循环是什么?

下面的代码,提前致谢

添加了这个 Groovy 片段

import groovy.json.JsonSlurper
def slurper = new JsonSlurper()
def response = context.expand( '${POST/instant-deal/get-applicable-request#Response}' ).toString()
def jsonRes = slurper.parseText(response)

RuleId = jsonRes.RuleId
RuleId.each { RuleID ->
    log.error "Rule IDs: " + RuleID
    assert RuleID != null
    assert RuleID instanceof Integer    
}

如果空 RuleId 无效则添加:

...
RuleId = jsonRes.RuleId
assert RuleId
...

是的,围绕空列表的循环将立即退出。

您正在做类似的事情:

def expected = [1,2,3]
def actual = myMethod() // returns a list of int
actual.each { x ->
   assert expected.contains(x)
}

如您所见,这表示 actual == [][1][1,3][3,2,1] -- 它的意思是,“我不actual 中需要任何内容​​,但是 中的任何内容都必须是 expected.

的成员

相反,如果您想确保 expected 的每个成员也在 actual 中,您应该围绕 expected 循环:

expected.each { x ->
   assert actual.contains(x)
}

这会检查 expected 的每个成员都存在于 actual 中,但不介意 actual 是否包含更多成员。因此它会通过 [1,2,3][3,2,1],但也会通过 [1,2,3,3][1,2,3,4] - 这可能是您需要的。

如果您想检查列表是否完全相同,只需使用 actual == expected(在 Groovy 中...在 Java 中您需要使用 .equals())

你究竟应该做什么,取决于你想要断言的确切内容。目前,您所描述的内容:"spot check each item in the response and check that each item is the correct data type." 应该 通过一个空列表,因为列表中的每个项目(即 none)都具有正确的类型。