O'Reilly logo

Spock: Up and Running, 1st Edition by Rob Fletcher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2. Specification Basics

Spock is a straightforward and expressive language for writing automated tests for software. It is based on the Groovy programming language but can be used to test code written in any language that runs on the Java Virtual Machine (JVM)—Java, Scala, Kotlin, even JavaScript. In this first chapter, we look at how to create specifications in Spock; how individual tests, or feature methods, are structured; how to make assertions; and how the lifecycle of a specification works.

If you’ve used JUnit or another unit testing framework before, some of the ideas might seem familiar. However, don’t worry if you haven’t. Although Spock is built on top of JUnit’s test runner, that’s really just to make the Spock specifications easy to run anywhere JUnit tests can run. The syntax used to express test code in Spock is pretty different.

Anatomy of a Specification

Spock test classes—known as specifications—are written in Groovy.

Here is a simple Spock specification:

import spock.lang.*

class IntegerSpec extends Specification {

  def "an integer can be incremented"() {
    given:
    int i = 1

    when:
    i++

    then:
    i == 2
  }
}

This is an extremely straightforward test that just ensures the integer increment operator –0— works as expected. If you know Java, there are probably some familiar things (the import statement, class and variable declarations, increment operator, and Boolean expression) and some less familiar things (the def keyword; weird-looking method names, given:,

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required