Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spock: Reusable Data Tables

Tags:

groovy

spock

Can I take a test like this and extract the where clause data table into a reusable block?

@Unroll
void "test that doSomething with #a and #b does not fail"(String a, String b) {
    when:
        doSomethingWithAandB(a, b)
    then:
        notThrown(Exception)
    where:
        a     | b
        "foo" | "bar"
        "foo" | "baz"
        "foo" | "foo"
}

something like this (pseudo code):

@Unroll
void "test that doSomethingElse with #a and #b does not fail"(String a, String b) {
    when:
        doSomethingElseWithAandB(a, b)
    then:
        notThrown(Exception)
    where:
        dataTable()
}

def dataTable(a, b) {  // this is now reusable in multiple tests
        a     | b
        "foo" | "bar"
        "foo" | "baz"
        "foo" | "foo"        
}
like image 715
Alessandro Scarlatti Avatar asked Oct 10 '17 13:10

Alessandro Scarlatti


1 Answers

Table-formatted data in where clause is actually parsed as a set of OR expressions at compile time, collected into list of lists and then transposed, so this:

where:
a | b | c
1 | 0 | 1
2 | 2 | 2
4 | 5 | 5

will be transformed into this:

where:
a << [1, 2, 4]
b << [0, 2, 5]
c << [1, 2, 5]

before the test methods are generated (see org.spockframework.compiler.WhereBlockRewriter for details). This var << list construct is referred to as "data pipe" in documentation.

Upgrading the existing answers a bit, as of Spock 1.1, one can shorten the code a bit using a construct called "Multi-Variable Data Pipes", which will transpose the table:

class SampleTest extends Specification {
    @Unroll
    def "max of #a and #b gives #c"() {
        expect:
        Math.max(a, b) == c
        where:
        [a, b, c] << dataTable()
    }

    static def dataTable() {
        [
                [1, 0, 1],
                [2, 2, 2],
                [4, 5, 5]
        ]
    }
}

Fun fact: while the docs on Syntactic Variations don't explain why, it is because the table rows are parsed as a set of OR expressions, the double bars can also be used -

where:
a | b || c
1 | 0 || 1
2 | 2 || 2
4 | 5 || 5
like image 166
jihor Avatar answered Oct 04 '22 14:10

jihor