Testing with Spring RestTemplate

Dave Townsend
unbounded.io
Published in
2 min readOct 11, 2016

--

Original post date Aug 29th, 2012

The Spring framework has made it trivial to consume RESTful resources by using their RestTemplate. I’ve been using the RestTemplate on a recent project and came accross a cool way to run unit tests by mocking out a REST server service. This is accomplished with a little help from the spring-test-mvc project. Currently, the compiled production version of this library existis the in the Spring Social project.

Getting the Dependencies

The Spring Social project contains a jar named spring-social-test-1.0.2.RELEASE (1.0.2 at the time of this writing). Just download the Spring Social Core modules and get it out of the bin directory. Or pull down the artifacts with your Gradle or Maven build to get the jar in your project.

Setting up the Tests

With the dependencies on your projects classpath you can quickly set up a MockRestSeverService and start testing your service calls against it.

The first thing that I have done is defined a URI, which can be anything it’s just needed for the service call. Next, HttpResponse headers are created for the server service, XML media type in this case. A RestTemplate is created and a MockRestServerService is constructed with the RestTemplate reference. The mock service’s URI and accept method are set along with the response body and headers. For the body, a Resource method is used that simply returns an XML file that is located in the same package as the test file. A mocked instance of a Booking object is created for the call but contains nothing.

Calls can now be made to the MockRestServerService just as if it were the real service. As you can see, the response is getting unmarshalled into a Booking object allowing you to make assertions on its validity.

Configuration Details

You may have noticed that there are no other Spring configurations mentioned. The RestTemplate alone will give you marshalling/unmarshalling of the common types that Spring supports by default. No other configuration is needed. My example is using JAXB2 (not shown) which is automatically supported as long as JAXB2 is on the classpath. All I had to do was annotate my Booking object model with the JAXB2 annotations.

The Spring Test MVC Project

It sounds like the plan is to move the spring-test-mvc project into the spring-test module for the 3.2 release. Here is the Jira the mentions that.

--

--