Spock is a testing framework building on the concepts of Behavior Driven Development (BDD). It uses the Groovy programming language to allow writing tests in a concise manner. It offers an alternative to commonly used testing frameworks like JUnit or TestNG.
Spock was created by Peter Niederwieser, a software engineer at Gradleware. Spock’s current version is 1.0.
Spock provides an interesting alternative to testing frameworks like JUnit or TestNG. In contrast to those tools, it uses the Groovy programming language. Groovy is a dynamic language that supports static-typing and static compilation. The main benefit of using Groovy is that it’s more concise and expressive than plain Java.
Some of the benefits of Spock are:
The benefits of using Spock don’t come without a price. It requires at least partially learning a new language: Groovy.
Lets get started with a simple (maybe a bit contrived) example. Suppose we want to develop a simple calculator that supports arithmetic operations.
A possible implementation for the plus
operation could look like this:
For using Spock with gradle, setup is as easy as this:
By this we’re enabling Groovy support for our project and include the Spock framework dependencies.
For our calculator example we can easily specify test cases with Spock. We setup our test object as an instance field and define a first feature method. Spock creates a new instance of our test object for each feature method.
Each feature method is divided in three blocks:
then
block asserts can be specified with ==
.If a test fails in Eclipse, expected and actual value as well as the used comparison operator are reported.
Exception testing is also pretty straightforward as shown in the next example.
Compared to JUnit’s @Test(expected=IllegalArgumentException.class)
or ExpectedException
rule that’s really a nice way to do exception testing. As thrown
returns the thrown exception we can also easily refine our expectations.
If we want to test multiple data combinations in one test, we can resort to Data Driven Testing. Spock supports this out of the box by using so called Data Tables. Due to Spock’s expressiveness, the next example is quite self-explanatory.
A data driven test consists of two blocks:
For each example in the table an isolated test is executed, the same way as if we would have defined separate test features.
In this post we’ve had a glance at the Spock testing framework. It provides a simple and clean API to write tests for Java classes in Groovy. We’ve seen that exception and data driven testing can be easily achieved with Spock.
More advanced topics like mocking or integration tests will be covered in one of the upcoming posts.