Search code examples
springunit-testingspock

How could we use hashmap as a variable in where block


I want to put a SET here, how? I googled this spock where block new HashSet did get any result.

    @Unroll
    def "Sample"() {
        expect:
            .....
        where:
        base | exponent || result1 | result2
        1    | 2        || 1 | {{I want to put a SET<ID> here, how?}}

    }

Solution

  • I think you are not just a Spock newbie (I noticed in your previous question) but also a Groovy newbie. No problem. :-) You should rather google for groovy set literal and find something like this page.

    In Spock you can either define the variables in the where: block as method parameters for your feature method (test method) including giving them types like this:

    @Unroll
    def "sample"(int base, int exponent, int result1, Set<Integer> result2) {
      expect:
      result2 instanceof Set
    
      where:
      base | exponent || result1 | result2
      1    | 2        || 1       | [1, 2, 3]
    }
    

    This would cast or coerce the list literal into a set. Or you can save a lot of typing and just use the Groovy as operator as shown on the page I linked to:

    @Unroll
    def "sample"() {
      expect:
      result2 instanceof Set
    
      where:
      base | exponent || result1 | result2
      1    | 2        || 1       | [1, 2, 3] as Set<Integer>
    }
    

    Instead of Set<Integer> you would use Set<Id> whatever your Id class might be.