Chapter 13. Testing REST APIs

REST (Representational State Transfer) is an architectural style for managing data over HTTP. In the past decade, REST—or approximations of it—have become one of the default mechanisms for interapplication communication. With the increasing popularity of stateful browser applications and microservice architectures, REST has become a fundamental component of internal- and external-facing applications. Although we would want to test as much application behavior as possible using simple, fast-running unit tests, end-to-end testing REST applications is a common requirement. Spock is more than equal to the task.

In this chapter, we look at building and testing a REST frontend for the Squawker application. The examples build on the Spring Boot application we’ve been building but are equally applicable to any platform.

The general approach for testing REST APIs is to use an HTTP client to connect to a running instance of the application, send realistic requests, and make assertions about the HTTP headers and response data that come back. That approach is applicable using any one of the many HTTP client libraries available (or even just a plain old Spring Boot includes a built-in HTTP client, TestRestTemplate, that the examples in this chapter use; however, it should not be difficult to translate lessons learned here to a different HTTP client API. There are numerous HTTP client libraries available for the JVM and their abstractions ...

Get Spock: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.