Here's a handy Kotline library for stubbing WireMock expectations.
Join the DZone community and get the full member experience.Join For Free
WireMock is a popular library for stubbing web services. It runs an HTTP server that acts as an actual web service. We just set up expectations and run the server.
In this tutorial, we will present the kotlin-wiremock library that provides a nice domain-specific language for stubbing WireMock expectations.
The first step is adding dependencies.
And now we can use kotlin-wiremock. Let's see the JUnit 4 example.
One of the basic features is url matching. Let's see an example: when calling a server with URL equal /users/1, the server returns a JSON body with Bob's response.
We can also use regular expressions for matching url. Notice that we can use method returnsJson so we don't need to specify the Conte-Type header manually.
Let's see how we can stub the post request. We return bobResponse only when request JSON body fulfills the following criteria:
- id key equalTo 1
- isAdmin key equalTo true
- points equalTo 3.0
- data object contains name key which starts with Bob string.
As you can see we have a full spectrum of solutions for mathing the request body. Note that the library gives us the possibility to check value types(string, integer, float, boolean).
We can also check headers and query params:
Look how priorities work, when we send Authorization header then the response is 200 otherwise the server replies with 403.
We can even simulate delays.
We can come up with more sophisticated scenarios. The first request returns bobResponse but we set flag toState to Alice. So the second response returns aliceResponse,
All features presented in this tutorial can be achieved via wireMock API.
But doesn't it look way better in Kotlin Wiremock DSL?
More examples can be found here:
Opinions expressed by DZone contributors are their own.