Print Shortlink

Spock for Groovy – I

The DSL capability of Groovy is a well known fact. When it comes to writing test cases for Groovy/Grails applications the API has always been not a very pleasant one. People talk about the unit tests being the best documentation for the code you write, but the assert methods and the lines of preparatory code before these assert conditions make the test cases poorly readable. Enter Spock.

Spock is a testing and specification framework. The USP of Spock is the expressive syntax, harnessing the power of DSL. You can write specifications( or specs) in Spock and run it using JUnit.

To begin with, you can create a Groovy project and add spock library and JUnit libraries to your build path. In my project I have spock-core-0.6-groovy-1.8.jar added to the classpath. The groovy compiler version is 1.8.
You can create a simple Calculator class with add method as shown below.

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

We would anyday prefer building the Calculator class using TDD, but that’s not the intention of this post. Let’s create a specification called CalculatorSpec and describe what we want to do using Spock. The CalculatorSpec would extend Specification class. A spec is composed of features. Each feature is implemented as a simple method that’s made up of blocks.
To keep it simple, the features are like the test methods inside a testcase. The CalculatorSpec with a feature is shown below.

import spock.lang.Specification;

class CalculatorSpec extends Specification{
	Calculator calc
	def "addition of 2 numbers"(){
			calc = new Calculator()
			31 == calc.add(15,16)	

The CalculatorSpec has a feature called “addition of 2 numbers”. You can compare this with the traditional test method such as def testAdditionOf2Numbers(). The feature method has the given and expect blocks. You can compare the expect block with the traditional assertTrue method. Running this spec as a JUnit test case gives you the expected results.

We’ve just scratched the surface of Spock. In the next few articles let’s build this CalculatorSpec to witness the real power of Spock.

Leave a Reply