Spock is a testing and specification framework for Java and Groovy applications. 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.
Spock Basics
The basic structure of a test class in Spock is a class that extends spock.lang.Specification and has multiple test methods (which may have descriptive String names).
Spock processes the test code and allows you 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
As shown, assertions are simply groovy conditional expressions. If the == expression returns false, the test will fail and Spock will give a detailed printout to explain why it failed.
Mocking
The expected behavior can be described by using a number or range multiplied by (*) the method call, as shown here. This means to expect this method is called two times; otherwise the test will fail.
The underscore (_) is treated like a wildcard much like in Scala (here the _ is just a field that refers to an object defined by Spock).
Lists or Tables of Data
Much like how JUnit has DataPoints and Theories, Spock allows you to use lists or tables of data in tests.
The overloaded << operator is used to provide a list for the event variable. Although it is a list here, anything that is Iterable could be used. This has the effect of running the test for each value in the list.
Ranges
The range 1.._ here means “one or more” times. You can also use _..3, for example, to mean “three or fewer” times.
In this case, the two columns (name and length) are used to substitute the corresponding variables in the expect block. Any number of columns can be used.
Expecting Exceptions
Summary
As you can see, Spock makes tests more concise and easy to read, includes mocking built-in, and, most importantly, makes the intentions of the test clear.