Search code examples
springgroovyspock

Access Spock data provider variable from inside where: block


I'm trying to access a where block variable from within the where block and it is not working. I'm thinking Spock doesn't allow this, but thought I'd give it a shot and see if anyone knows how to do it.

where:
testNumber << Stream.iterate(1, n -> n).iterator()
test << Stream.generate(() -> { testNumber > 15 }).iterator()

Result:

No such property: testNumber for class

If this isn't possible and someone has an alternative way to accomplish something similar I'm open to that. Basically I'm trying to make this test easier to manage, because keeping track of multiple arrays of 15-20 booleans is a bit of a pain:

testNumber << [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
post << [false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true]
postWeekend << [true, true, true, true, true, true, false, false, false, false, false, false, false, false, false]
dividendReinvested << [true, false, true, false, true, true, false, true, true, true, true, true, true, true, true]
createCCB << [false, false, false, false, false, false, false, false, false, false, false, false, false, false, true]
ntd << [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]

But many of them I can set up based on the test number instead, if I can access it (and having the test number available also makes it easy to determine which test failed).


Solution

  • It looks like you want to calculate something based on testNumber. You can use data variables for that.

    Another problem is that you are using an infinite stream, which will not terminate before the jvm will run out of memory. So you need to either use .limit(20) or just use a groovy range to define it more succinctly.

    import spock.lang.*
    
    class ASpec extends Specification {
      def "hello world"() {
        expect: 
        testNumber > 15 == test
          
        where:
        testNumber << (1..20)
        test = testNumber > 15 
      }
    }
    

    Try it in the Groovy Web Console.

    If that isn't what you wanted then you should update your question as @kriegaex suggested to tell us what you actually want to achieve.