Search code examples
unit-testingtestinggroovyspock

Reiterate over Spock where block?


We are using rest assured with Spock for our API testing. We have a situation where we are reading in data from a CSV file. So for this case let's pretend we are reading in 10 rows of data. Is there a way we can repeat this single test, for these 10 rows of data, for a given amount of "companies"? For example:

@Unroll
def "example test"() {
    when:
    //do something here

    then:
    //check something here

    where:
    row << functionalUtils.getRecordsFromCsv(csvFile)
}

This will run the test for however many rows are in the CSV file, so if there are 10 rows in the CSV file, it will run 10 times.

But let's say we have 4 companies we support that all have the same data and we want to verify all 4 companies are correct. Instead of making that CSV file 40 rows (repeating the same 10 lines 4 times) we want to repeat this test 4 times with the 4 companies. Something like

@Unroll
def "example test"() {
    when:
    //do something here

    then:
    //check something here

    where:
    company << ["company a","company b","company c","company d"]
    row << functionalUtils.getRecordsFromCsv(csvFile)
}

Am I making this harder than it is? Is this even possible? I know this is not correct and this will error, I'm just trying to demonstrate what I'm trying to do.


Solution

  • If all companies have the same data in the csv file, you can use Groovy's combinations() together with multi variable data pipes in Spock.

    where:
    [row, company] << [
        functionalUtils.getRecordsFromCsv(csvFile),
        ["company a","company b","company c","company d"]
    ].combinations()