Skip to main content

REST API mocking with Wiremock

Probably every developer or tester have used mocks at least once in their daily professional work. Functionality mocking is an excellent way to improve development process of integrated systems production, or testing heavy dependent application functionalities. With the growth of popularity of REST webservices, API mocking is becoming hot topic.

In this article I would like to introduce a simple getting-started tutorial of setting basic standalone REST API mock server with Wiremock on your local machine. Wiremock is a simple library written in Java for mocking web services.

Installation 

To run standalone wiremock server, download jar from here and run:

$ java -jar wiremock-1.55-standalone.jar

you should see:


This means that wiremock has started an empty mock server on localhost on port 8080. After you navigate to http://localhost:8080/__admin/ in your browser, you should get empty mappings entity:


You can also change default port by adding --port parameter:

$ java -jar wiremock-1.55-standalone.jar --port 9090

Another important feature is set verbose logging to stdout:

$ java -jar wiremock-1.55-standalone.jar --verbose

Adding mappings 

Next step is to add a request and response which we want to mock. Let us assume that our task is to mock API consisting of two methods:

First method:

  • request:


  • response:


Second method:

  • request:


  • response:


You may have noticed that wiremock had already generated two empty folders in it’s home directory. To add new mapping to our mock, create new json file getUser.json in mappings folder with the following content:


Above example should be pretty straightforward. Firstly, in request section, you define the URI under which you want to mock response, and the type of HTTP method. Then, in the response section, you specify HTTP status, headers and response body. If you want to use response body in json, remember to escape necessary characters. Nothing stands in our way to and some parametrization to the url query params. You can use regular expressions for that:

"request": { 
    "urlPattern": "/user/[0-9]+", 
    "method": "GET" 
}

After creating a new mapping file, restart wiremock jar and you’re ready to go. You can test your mock with some HTTP client like Postman or with use of simple curl:


Our first method mock is ready. Lets move to second method, which use POST request. The main difference here is that we have to define request body content in mock definition. Full snippet below:


Immediately apparent this code differs from the previous one. Main difference is method type, which is POST obviously, and bodyPatterns section, where we specify pattern for body request. You can also use here regular expressions, or apply some other method, like matches, doesNotMatch, etc:

"request": { 
    "urlPattern": "/addNewUser", 
    "method": "POST", 
    "bodyPatterns" : [ {
        "matches" : ".*status=ok.*"
    }, {
        "doesNotMatch" : ".*!@#$%.*"
    }, ] 
}

Of course it’s just an basic example of usage, for complete reference please visit official documentation. Let’s restart wiremock server and test our new method mock with curl (or you can perform similar test with Postman client again):


Our second method is good to go! At this point, when you have fully functional standalone mock, you can run wiremock server locally and create automated webservice tests, while developers create real implementation. You can also use mocks of your application external dependencies, and then deploy your project on external host and test your system flow dependency without integration issues.

Feeding on the go 

Wiremock standalone server have great feature of feeding your server with new mappings without creating new configuration files or restarting server. If you want to add on quickly new method mock to your server, but you do not necessarily want to store this as a new mapping in your configuration files, you can just add new method mock by sending it with curl to your wiremock server. Here’s an example of adding simple ping-pong health check to your mock server:

curl -X POST –data '{ "request": { "url": "/ping", "method": "GET" }, "response": { "status": 200, "body": "pong!\n" }}' http://localhost:8080/__admin/mappings/new

this request adds new GET method to wiremock with /ping endpoint. Mock should respond as follows:


Obviously your new /ping method will disappear after server restart. To add it permanently you have to add new entry in mappings files.

Continue reading 

If you want to continue reading and expand your knowledge in area of REST and microservices, I recommend you these books:
  • Building Microservices – one of the most important books for me, everything you want to know about microservices is here
  • Java For Testers: Learn Java fundamentals fast – test automation does not require complex programming knowledge. Learn fundamentals of Java for test automation. From tester to testers!
  • RESTful Web APIs – another great book about REST architecture. Lots of practical knowledge about designing and consuming RESTful APIs


Summary 

Mocking in today’s software development isn’t only a handy feature. It’s core practice, that every programmer and test automation developer should be familiar with. Wiremock is excellent and super fast tool for setting mocks. In this article I cover only standalone aspect of it, but wiremock has much more to offer, so I encourage you to visit official documentation. I will cover also other use cases of wiremock in future posts. If you have any questions, feel free to leave a comment.


Popular posts from this blog

Testing Asynchronous APIs: Awaitility tutorial

Despite the growing popularity of test automation, most of it is still likely to be done on the frontend side of application. While GUI is a single layer that puts all the pieces together, focusing your automation efforts on the backend side requires dealing with distributed calls, concurrency, handling their diversity and integration. Backend test automation is especially popular in the microservices architecture, with testing REST API’s. I’ve noticed that dealing with asynchronous events is particularly considered as challenging. In this article I want to cover basic usage of Awaitility – simple java library for testing asynchronous events. All the code examples are written in groovy and our REST client is Rest-Assured. Synchronous vs Asynchronous  In simple words, synchronous communication is when the API calls are dependent and their order matters, while asynchronous communication is when the API calls are independent. Quoting Apigee definition: Synchronous  If a

Rerun Flaky Tests – Spock Retry

One question I get asked a lot is how you can automatically rerun your test on failure. This is a typical case for heavy, functional test scenarios, which are often flaky. While test flakiness and its management is crucial and extensive matter itself, in this post I want to give a shout to the extremely simple yet useful library: Spock-Retry. It introduce possibility to create retry policies for Spock tests, without any additional custom-rules implementation – just one annotation. If you are not a fan of Spock testing framework and you prefer JUnit – stay tuned! I will post analogous bit about rerunning JUnit tests soon. Instalation  If you are an maven user, add following dependency: <dependency>       < groupId > com.anotherchrisberry < /groupId >       < artifactId > spock-retry < /artifactId >       < version > 0.6.2 < /version >       < type > pom < /type >   </dependency> For gradle users:

Performance Testing – Vegeta Attack!

Performance testing is crucial field of modern software development. Taking into account that in today’s world majority of app’s communication is web-based, it turns out to be even more important. However, it still enjoys less interest than automated functional testing, and publications on load testing subject usually focus on mature and complex tools like JMeter or Gatling. In this post I’d like to introduce command line usage of a super simple and lightweight tool for performance testing of HTTP services, which is Vegeta. Who is Vegeta  Besides Dragon Ball’s character, Vegeta is a simple load testing tool written in GO, that can be used both from command line and as an external library in your project. In order to use Vegeta, download executables from here . It is recommended to set environment variable for ease of use.  For Mac users, you can download vegeta directly from Homebrew repositories: $ brew update && brew install vegeta Vegeta’s Arsenal  Usage