Unit tests with Spock

June 30, 2017

This article has first appeared in Today Software Magazine

Why Spock?

When we first started working on our project at work, we searched for an easy-to-use tool that would help us write readable and concise tests. We chose Spock, because in combination with Groovy it provided exactly what we needed: readable BDD-style tests that we could write fast and change easily. Keep in mind that Spock can also be used in combination with Java, but has a great synergy with Groovy.

All the examples in this article are written in Groovy, but fear not! If you are a little bit familiar with Java, you will see that you can read Groovy code. Because our project’s tests examples would have been too complicated for a Spock introduction, I have chosen examples from a kata I coded to practice TDD.

1. Getting started

Adding Spock with Gradle is easy. This is my build.gradle file:

apply plugin: ‘groovy’

repositories {



dependencies {







// for spock reports




Write the first falling test:

import spock.lang.Specification

class SeeIfItWorksSpec extends Specification {

   def “it should fail”() {





The output is:

Condition not satisfied:


Afterwards, replace false with true. If the output is “Tests PASSED”, your setup is complete.

Read the complete article here.

Categorised in: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *