Print Shortlink

Spock for Groovy – IV

In this last post of using Spock with Groovy, let’s learn to use mock objects.
We’ll continue to use the Calculator class. The Calculator class has the add method that returns the sum of two numbers. Let’s modify the add method to store the results of the operation in a store. For this purpose, we’ll use an interface called CalcStore that has a store method as shown below.

//CalcStore.groovy
interface CalcStore {
	boolean store(operation,num1,num2,result)
}

The Calculator class that uses the CalcStore is shown below.

 
//Calculator.groovy
class Calculator {
	CalcStore calcStore
	def add(num1,num2){
		def sum = num1 + num2
		storeResults("Addition",num1,num2,sum)
		sum
	}
	def storeResults(operation,num1,num2,result){
		calcStore.store(operation, num1, num2, result)
	}
}

Let’s create the CalculatorSpec with a feature to test the add method. We’ll mock the behaviour of store function here as shown below.

class CalculatorSpec extends Specification{
	Calculator calc
	def calcStoreMock
	def setup(){
		calc = new Calculator()
		calcStoreMock = Mock(CalcStore)
		calc.calcStore = calcStoreMock
	}
	def "store results"(){
		given:
			1 * calcStoreMock.store("Addition",50,50,100) >> true
			calc.calcStore = calcStoreMock
				
		expect:
			calc.add(50, 50)
	}
	def cleanup(){
		calc = null;
	}
}

In the setup method we mock the CalcStore and assign it to the calculator instance. In the given block of the “store results” feature, we record the behaviour of store function to accept the 4 parameters and return true. The “1 * calcMockStore” indicates that the method will be called once.

This is just a simple example of mocking in Groovy.

Leave a Reply