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 {

    mavenCentral()

}

dependencies {

    testCompile(

            ‘junit:junit:4.12’,

            ‘org.codehaus.groovy:groovy-all:2.4.4’,

            ‘org.spockframework:spock-core:1.0-groovy-2.4’,

    )

    testRuntime(

// for spock reports

            ‘com.athaydes:spock-reports:1.2.7’

    )

}

Write the first falling test:

import spock.lang.Specification

class SeeIfItWorksSpec extends Specification {

   def “it should fail”() {

      expect:

      false

   }

}

The output is:

Condition not satisfied:

false

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 *