Xelian
Xelian

Reputation: 17198

Dynamically change data in where clause using Spock

I have to iterate over some map and for every key, to make checks based on the current element,so I tried:

class TestSuite extends Specification {
@Shared
def elements

def setupSpec{
    elements =  ['a.txt':1,'b.txt':2]
}

@Unroll
def 'test for #first and #second'() {
expect:
  true

where:
  [first, second] << [elements.keySet(), elements[first].findResults { key, value->
        key.substring(key.indexOf('.') + 1)
    }].combinations()
  }
}

but Spock fails and says that first is unknown. How can I do that so that the two values to be in the name of the test so in unroll to see their values?

Edited

Upvotes: 0

Views: 2522

Answers (1)

Luis Mu&#241;iz
Luis Mu&#241;iz

Reputation: 4811

I have to say that your code does not make much sense. I have hesistated to just downvote your question instead of replying. There is so much wrong with this question. Just shows a lack of effort in formulating your question.

The first red flag is that you did not even try to compile this code. You have a map with String keys and integer values:

  • your map litteral does not compile. key/value pairs are separated by commas in groovy.
  • You call methods of this map that (Map#key() ?) are not in the API.

Then, there are two possibilities, either your imaginary key() method returns the key, which does not make any sense, because first IS the key already, or key() returns the value, which is really bad naming. But bad naming is not all, because then you call toUpperCase() on an integer.... This is a mess!

Nevertheless I am going to show you how you can base the value of a where variable on the value of another where variable, because that's the core part of your question, with

import spock.lang.*

class MyFirstSpec extends Specification {
    //elements needs to be Shared to be used in a where block
    @Shared
    def elements = ['a':1,'b':2]

    @Unroll
    def 'test for #first and #second and #third'() {
        expect:
        true

        where:
        first << elements.keySet()

        and:
        second = elements[first]
        third  = first.toUpperCase()
    }
}

​resulting in

- test for a and 1  and A
- test for b and 2  and B

Upvotes: 2

Related Questions