Learn about the Spock framework.

We'll cover the following

What is Spock?

Spock is a testing framework for Java and Groovy applications. The Spock website has this to say about Spock:

“What makes it stand out from the crowd is its beautiful and highly expressive specification language. Thanks to its JUnit runner, Spock is compatible with most IDEs, build tools, and continuous integration servers. Spock is inspired from JUnit, RSpec, jMock, Mockito, Groovy, Scala, Vulcans, and other fascinating life forms.”

The basic structure of a test class in Spock is a class that extends specification and has multiple methods with strings for names.

Spock processes the test code and allows us to use a simple groovy syntax to specify tests.

Each test is composed of labeled blocks of code with labels like when, then, and where. The best way to learn Spock is with examples.

A simple test

Let’s start by recreating a simple test from the chapter on JUnit:

def "toString yields the String representation"() {
     def array = ['a', 'b', 'c'] as String[]
     def arrayWrapper = new ArrayWrapper<String>(array);
     arrayWrapper.toString() == '[a, b, c]'

As shown above, assertions are simply Groovy conditional expressions. If the above == expression returns false, the test will fail and Spock will give a detailed printout to explain why. In the absence of any when clause, you can use the expect clause instead of then. For example:

def "empty list size is zero"() {
  expect: [].size() == 0

Get hands-on with 1200+ tech skills courses.