In Spock, how to select certain rows in data table to run, based on some condition?

Viewed 146

Is there a way to select certain rows in data table to run based on its value?

For example, sometimes I wish to run all the rows where a<5, other times I wish to run the rest of the rows.

It happens in testing that there can be hundreds of rows of data in the table. And most of the time I just want to run a small subset of it. But I don't want to just duplicate this method, and split the data into two tables.

class Math extends Specification {
    def "maximum of two numbers"(int a, int b, int c) {
        expect:
        Math.max(a, b) == c

        where:
        a | b | c
        1 | 3 | 3
        7 | 4 | 4
        0 | 0 | 0
    }
}

What can I try to solve this?

1 Answers

If you use Spock 2.0 then you can use @Requires to filter on data variables.

class Example extends Specification {
    @Requires({ a > 5})
    def "maximum of two numbers"() {
        expect:
        Math.max(a, b) == c

        where:
        a | b | c
        1 | 3 | 3
        7 | 4 | 7
        0 | 0 | 0
    }
}

Result

╷
└─ Spock ✔
   └─ Example ✔
      └─ maximum of two numbers ✔
         ├─ maximum of two numbers [a: 1, b: 3, c: 3, #0] ■ Ignored via @Requires
         ├─ maximum of two numbers [a: 7, b: 4, c: 7, #1] ✔
         └─ maximum of two numbers [a: 0, b: 0, c: 0, #2] ■ Ignored via @Requires

One thing to note, that this will probably change in Spock 2.1 to @Requires({ data.a > 5}) here is the relevant issue.

Related