Introduction to Spock Framework

introduction spock framework

What is Spock Framework anyway?

Spock Framework is an open source testing and specification framework for Java and Groovy applications. It lets you write concise, expressive tests, Behaviour Driven Development (BDD) like form, what makes your test more clear. Spock is compatible with most IDEs, build tools, and continuous integration servers. Spock is inspired from JUnit, jMock, RSpec, Groovy, Scala.

Understanding How the Spock Framework Works

Suppose we have a Publisher class that sends messages to its Subscribers:

And the respective unit test class:

In Spock Framework we don’t have tests, we have specifications. A specification is represented as a Groovy class that extends from “spock.lang.Specification”, which is actually a JUnit class.

Fixture Methods

Fixture methods are optional and they are responsible for setting up and cleaning up the environment.

Feature Methods

They are the heart of a specification, here is the place where we describe the features that we expect to find in the system under test, this structure is common in BDD.

Blocks

It is an alias for setup, basically in this block we want specify the context within which we would like to test a functionality. Here we specify the parameters of our system/component that affect a functionality that is under the test:

‘When’ and ‘Then’ blocks always occur together, they are the stimulus and expected response. ‘When’ blocks may contain any arbitrary code, ‘Then’ blocks are restricted to conditions, exception conditions, interactions and variables definitions. In the example above we expect one interaction for each subscriber where the method receive is called with the parameter ‘hello’.
Another interesting point, we could make our specification more readable by adding text descriptions after the ‘When’ and ‘Then’ labels:

Mocking

Spock actually comes with it’s own mocking framework to make interaction-based tests easier to write and more readable.
Below is two possible ways to create a mock:

Setup how our mocks will behave:

A More Complex Example

Below is a more complex example that demonstrates other options that we have:

Conclusion

It’s interesting to observe how the Spock Framework combines many good ideas from different test frameworks and delivers a very intuitive way to write meaningful specifications.

Spock turns the tests more instructive, better arranged, easier to understand and in advance, it forces the developer to write tests in a form of BDD, and of course, the most important is that writing tests became a gratifying reward and extremely pleasurable.