Ratpacked: Using Spring Cloud Contract To Implement Server

Spring Cloud Contract is a project that allows to write a contract for a service using a Groovy DSL. In the contract we describe the expected requests and responses for the service. From this contract a stub is generated that can be used by a client application to test the code that invokes the service. Spring Cloud Contract also generates tests based on the contract for the service implementation. Let’s see how we can use the generated tests for the service implementation for a Ratpack application.

Spring Cloud Contract comes with a Gradle plugin. This plugin adds the task generateContractTests that creates tests based on the contract we write. There are also tasks to create the stub for a client application, but here we focus on the server implementation. In the following Gradle build file for our Ratpack application we use the Spring Cloud Contract Gradle plugin. We configure the plugin to use Spock as framework for the generated tests.

It is time to write some contracts. We have a very basic example, because we want to focus on how to use Spring Cloud Contract with Ratpack and we don’t want to look into all the nice features of Spring Cloud Contract itself. In the directory src/test/resources/contracts/pirate we add a contract for the endpoint /drink:

We add a second contract for an endpoint /walk:

The last step for generating the Spock specifications based on these contracts is to define a base class for the tests. Inside the base class we use Ratpack’s support for functional testing. We define our application with MainClassApplicationUnderTest and use the getAddress method to start the application and to get the port that is used for the application. The generated specifications rely on RestAssured to invoke the HTTP endpoints, so we assign the port to RestAssured:

We can write the implementation for the PirateApp application and use Gradle’s check tasks to let Spring Cloud Contract generate the specification and run the specifications. The specification that is generated can be found in build/generated-test-sources and looks like this:

If we run Gradle’s check task we can see the Spring Cloud Contract plugin tasks are executed as well:

The code for the complete application is on Github.

Written with Ratpack 1.4.5 and Spring Cloud Contract 1.0.3.RELEASE.

Original blog post

This entry was posted in Coding, Ratpack, Spring and tagged , by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *