是否可以在 spock 的 where 块中使用给定块中定义的列表?

Is it possible to use a list defined in a given block in a where block in spock?

例如:

given: "a list and a variable"
def checkThese = someStaticFunctionThatReturnsAList()
a = 5

expect: "a is greater than b"
a > b

where: "B is a list defined in given"
b << checkThese
//b << [1,2,3,4,5] will work, the above will not

这将失败并说没有这样的 属性 checkThese。我怎样才能做到这一点?

它不起作用,因为 where: 块虽然在规范方法中最后写入,但实际上首先执行,因为它用于 "data driven testing"。它实际上有助于多次调用您的方法(对于您在那里设置的每个数据迭代)。

所以在你的情况下:

given: "a list and a variable"
def checkThese = someStaticFunctionThatReturnsAList() // this line will actually get executed every time your spec method runs
a = 5

expect: "a is greater than b"
a > b

where: "B is a list defined in given"
b << checkThese // will not work (because the given block is not executed yet and the variable is not created yet and not accessible
b << [1,2,3,4,5] // works because you're setting up the data explicitly
b << someStaticFunctionThatReturnsAList() // will also work