WireMock is a library for stubbing and mocking web services. It makes heavy use of the builder pattern and has a very expressive syntax. But with Groovy’s operator overloading, it can be improved even further.
Groovy’s extension modules allow adding new methods to existing classes without touching the original source code. And that even works with operator overloading. This article describes how to use this toolset to simplify WireMock’s syntax even further.
If you are not familiar with extension modules, find a short introduction here. Operator overloading is described here.
An API endpoint is defined that returns http code 200 with empty response. A helper method calls the API and it is verified that the endpoint was called at least once.
We can also see WireMockRule as a map of endpoints where getting values returns all invocations with that endpoint and assigning values configures the endpoint’s response.
Depending on the most common use cases in the application under test, more simplifications can be set up. For example, assignment of a map could lead to a response with status code 200 and serialised JSON response body.
WireMock has some support for JSON matching, but there is no built in way to get the parsed JSON body from a request. Following two extension methods add this functionality. The first one returns the JSON body of an individual request, the second one is a convenience method to get it from the first of several responses.
And this test is using jsonBody in combination with previously implemented map access.
The call to server[API_POST_REQUEST].jsonBody returns a Map in our case and Spock’s with method make verification of its entries very easy.
In this article, we’ve seen how to simplify WireMock syntax using extension modules and operator overloading. It only scratches on the surface of what is possible. More operators and methods can be added to define your application specific DSL. If you have more ideas on how to extend the syntax of WireMock, then please leave a comment.
The full source is as always available on Github.