Testing Spring Boot Applications with Spock

As a Grails developer, I love the Spock testing framework. Spock is a testing and specification framework that fully leverages groovy to help you write succinct and highly expressive tests. You can read more about Spock in the Framework documentation.

In this post, I want to show how you can use Spock to add easily readable tests for your Spring Boot applications.

Follow the steps of the Java portion of the tutorial until you have a fully running application. If you wish to skip this step, the github repo comes with a completed example under the complete directory.

Add Spock and groovy to your Gradle Build

As we’re going to write our tests in Groovy, we are going to add the groovy plugin for Gradle. We are also going to replace the jUnit dependency with Spock.

Change the line that says

apply plugin 'java'

to

apply plugin 'groovy'

Next, change the jUnit dependency to the spock and groovy dependencies.

In this file, we extend Spock Specification so that Spock knows this is a test.

We have a feature in Spock we’re testing called “testing spock works”. This is a descriptive method that describes the thing we are testing. I hope you can see how nice it is to express the method in natural language instead of programmese.

Starting and shutting down the Application Server

In the same vein as the jUnit test, we start up an application server when we enter the test and shut it off when the test is finished. Instead of the @BeforeClass and @AfterClass annotations in jUnit, we simply call setupSpec() and cleanupSpec() in Spock.

In this output, you can see where the test expression fails and see the output from each level of the test. This is very useful for error diagnosis. Moreover, IntelliJ has really good support for this, so when I click on see difference, I am presented with a comparison dialog:

AutoCleanup

I can make my test simpler by getting rid of my cleanupSpec and changing my context definition to the following:

@Shared
@AutoCleanup
ConfigurableApplicationContext context

The autoCleanup feature simply calls close on the context once my spec has finished. It is quite handy.

Adding more features

Let’s say I want to add another endpoint to my application so that it reverses the input that I send to the controller. True to proper TDD, I will first write a failing Spock test:

Here, I use a handy feature in Spock called Data Tables. This allows me to define multiple iterations of a test and define the data for the test in each row of the where label. Data tables are really powerful and I recommend you read up on them here.