Testing Microservices with WireMock

In this series we will look at how WireMock can help the development and testing of Microservices. The first part will focus on a standalone setup to understand what WireMock is and what features it provides. After that we will create a simple Spring Boot app and test it using JUnit and WireMock.

Introduction

When testing microservices we often encounter problems with testing external webservices. One way to solve this is by creating a mock service where you can mock the behaviour of the service you’re calling. However, this takes up a lot of time. This is where WireMock comes in. It enables you to easily create mocked API’s by defining requests and responses. WireMock is not only useful for testing purposes. It could be also used to mock an API that doesn’t exist for instance.

Getting started

To get started I’ve created a Spring Boot app on everyones (but especially Josh Long’s) favorite website; start.spring.io , with only the web module selected. This will give us a working web app that doesn’t do anything, which is fine for now.

After that I’ve added the following dependency to the POM:

That’s it, we’re ready to write our first WireMock tests.

Wiremock structure

To start a WireMock server, the only thing you have to do is use the following lines of code:

By default WireMock will load mapping files from the mappings directory in your resources folder. In the mappings folder we can place JSON files that describe the request and response that we want WireMock to mock. Let’s create a file called firstRequest.json that has the following contents:

When we start the application and do a GET request to http://localhost:8089/api/first it will return Hello, Sourcelabs!

Most API’s these days will give a response in JSON or XML format. Luckily, WireMock has a function where you can respond with the contents of a file in the response body. To achieve this we can change the response to something like:

Just like the mappings folder we can create a __files folder that contains all files we might want to serve as a response. Let’s create a file called firstResponse.json containing: {"message": "Hello, Sourcelabs!"}Now try the curl command again and we’ll see that we now get a JSON message as response. WireMock offers a rich set of features for matching requests, for more information about this check http://wiremock.org/docs/request-matching/.

Did you enjoy this content? We have got more on the way! Sign up here for regular updates!

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *