In the previous post, we got introduced to **Spock** framework. We created a **Calculator **class with an add method and a spec called **CalculatorSpec **with a feature to test the add method.

Let’s add some more test features in our CalculatorSpec to see the use of Spock. The Calculator.groovy that we want to spock is given below.

class Calculator { def add(num1,num2){ num1 + num2 } }

Let’s write a test feature where we pass a set of numbers and test for the addition result. In this feature, we’ll use the ‘**where**‘ block. The CalculatorSpec.groovy with this feature is shown below.

//CalculatorSpec.groovy import spock.lang.Specification; class CalculatorSpec extends Specification{ Calculator calc def "adding a set of numbers"(){ given: calc = new Calculator() expect: calc.add(num1,num2) == sum where: num1 << [1,2,3] num2 << [30,40,50] sum << [31,42,53] } //We wrote this feature in the previous post def "addition of 2 numbers"(){ given: calc = new Calculator() expect: 31 == calc.add(15,16) } }

The feature “**adding a set of numbers**” has a where block with 3 lists. The block will be run calc.add(num1,num2) == sum will be run iteratively by picking one item from each of these 3 lists. Pretty intuitive!!!

Let’s refactor the features to initialize the calc object in **setup** and **cleanup** methods as shown below.

import spock.lang.Specification; class CalculatorSpec extends Specification{ Calculator calc def setup(){ calc = new Calculator() } def cleanup(){ calc = null; } def "addition of 2 numbers"(){ expect: 31 == calc.add(15,16) } def "adding a set of numbers"(){ expect: calc.add(num1,num2) == sum where: num1 << [1,2,3] num2 << [30,40,50] sum << [31,42,53] } }

We’ll continue learning more…