January 25, 2011

Suppose we get assigned to an existing Java project and we want to use Spock for writing our tests (of course!). In this post we learn the steps we need to take to achieve this. We assume the Java project is built with Maven and imported into SpringSource Tool Suite (or Eclipse). For an easier way to add Spock to STS/Eclipse using Gradle we can read this blog post written by Ken Kousen.

First we start with our Java project. The project for this sample is very simple. We only have one interface and an implementation class for finding a username in a list of users. The sources for this post can be found at Github. The following pom.xml is used:

Notice we must add the gmaven-plugin and spock-maven plugin to the plugins section. We must also add the spock-core dependency to our project. This is all we need to do to be able to run Spock specifications with Maven. But we need to do some extra steps to be able to run our Spock specifications from SpringSource Tool Suite.

First we add the directory src/test/groovy (which is used to save the Spock specifications in) to our project. Then we assign this new directory as source directory to the project. We open the properties of our project and select Java Build Path:

Next we click on the Add Folder... button and select the Create New Folder... button. We create the folder src/test/groovy:

We click on the Finish button and now we can select the newly created folder as a new source folder:

Now comes an important step, because we must change the Output folder of our newly created source folder. We select it and press the Edit... button. In the dialog window we select the radio button Specific output folder and fill in target/test-classes. If we don't change the output folder then STS cannot determine changes in the sources if we use the Run As | JUnit Test action.

Now we have added a new source folder to our project and assigned a correct output folder for the compiled class files:

Next we must make our Java project a Groovy project in STS. We right-click on our project and select Configure | Convert to Groovy Project:

Okay, STS is now ready for our Spock specifications! We write the following specification and save it as src/test/groovy/com/mrhaki/app/services/UserServiceImplSpec.groovy: