Mahbub Rahman Mahbub Rahman - 2 months ago 23
Groovy Question

Spock: How to input string values in a data pipe

I googled a lot but did not find a single example of populating input data with string values in a data pipe.

Can someone give an example of how to do it?

I used:

[a,b,c] << ["aaa","bbb","ccc"]


but getting error.

Answer

Assuming you want to run the test 3 times, with the same variable assigned "aaa" for the first run, "bbb" for the second, and "ccc" for the third, you you would do it like this:

where:
variableName << ["aaa","bbb","ccc"] 

Here's a complete example from one of my projects:

class PhoneNumberConverterSpec extends Specification {

    private PhoneNumberConverter phoneNumberConverter = PhoneNumberConverter.instance

    @Unroll('convert invalid phone number #input')
    def 'attempt to convert invalid phone numbers to canonical format'() {

        expect:
        !phoneNumberConverter.canConvert(input)

        where:
        input << [null, 6, '353', '9999999']
    }
}

If on the other hand, you want to run the test only once and assign values to 3 different variables then there's really no point in using data pipes, just declare and assign the variables as you would in regular Groovy code.

Comments