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

时间:2016-09-28 20:16:09

标签: groovy 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。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:1)

它不起作用,因为尽管在spec方法中最后写的where:块实际上是先执行的,因为它用于“数据驱动测试”。它实际上有助于多次调用您的方法(对于您在那里设置的每个数据迭代)。

所以在你的情况下:

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