Unroll annotation in Spock Testing framework

Spock is a testing framework for Java and Groovy application. This is a best alternative to Junit. In this post, Let’s see how we can use Unroll annotation of spock framework with an example.

Let’s assume that we have a class called “MathOperation” contains methods to perform arithmetic operations and we have a spock test class to test those methods.

MathOperation.java


public class MathOperation {
    
    private MathOperation(){
        
    }

    public static int sum(int a, int b) {
        return a + b;
    }

    public static int divide(int a, int b) {
        return a / b;
    }

    public static int multiply(int a, int b) {
        return a * b;
    }

    public static int minus(int a, int b) {
        return a - b;
    }
}


The spock test for testing the ‘sum’ method is as below.


import spock.lang.Specification

class MathOperationSpec extends Specification {

    def "sum of two numbers"() {

        expect:
        int actual = MathOperation.sum(num1, num2);
        actual == expected

        where:

        num1 | num2 | expected
        1    | 2    | 3
        2    | 3    | 5
    }

When we run this test case, the test run will look like below,

spock-withouunroll

When an error happened, we are not sure which line caused the problem. It will report only the error method but would not give the information about the exact line. The Unroll annotation helps to fix this problem. Unroll annotation has no effect on how the method gets executed but its an alternation in reporting.

Lets rewrite the above test with Unroll annotation as below.


import spock.lang.Specification
import spock.lang.Unroll

class MathOperationSpec extends Specification {

    @Unroll
    def "sum of two numbers #num1 #num2"() {

        expect:
        int actual = MathOperation.sum(num1, num2);
        actual == expected

        where:

        num1 | num2 | expected
        1    | 2    | 3
        2    | 3    | 5
    }
}

When we run the above one, it will look like below,
spock-withunroll