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

Notes after TestingCup 2018

On May 28-29th I attended TestingCup conference in Łódź. Having quite unique perspective: this was my second year in row as a Speaker at this conference I want to share some thoughts on the event. Dust has settled, lets go! 



Championship Originally TestingCup is a software testing championship. Wait, what? Yes, the formula is unique: teams and individuals from all around Poland are competing in finding the most bugs and defects in specially prepared application - Mr. Buggy. I don’t have specific data, but since this year’s conference was all english I guess competitors were not only from Poland. As a spectator, I must say that the whole competition looked very professional. There were team shirts and names, podium and trophies (gold cup and cash). 
Some cons? Testing championship is held at the first day of the conference. So this is already a conference, but if you’re not taking part in the championship… there’s not much to do, since all the talks are in the next day. Organizers are aw…

REST-Assured framework overview

In modern software development, REST services becomes most popular choice for implementing distributed and scalable web application. They are light and easy to maintain, which results in faster and more effective implementation and system integration.
I recommend you also my other posts about REST-Assured and building microservice’s test automation frameworks: REST-Assured: going deeperBuilding microservices testing framework
With the increase popularity of RESTful services, there is a need for fast and lightweight tool for REST webservices testing automation. One of the most popular choice is Rest-Assured framework from Jayway. It introduces simplicity of testing web services from dynamic languages like groovy or ruby to java. In this post we will get our hands dirty and write automatic test in Rest-Assured framework.
In order to create complete implementation of automated tests in Rest-Assured framework, we need to write our code against some example API. We’ll use standalone Wiremock m…

Building microservices testing framework

RESTful services and microservice architecture in general are big trends in the industry right now. I’ve noticed it also from this blog’s traffic analytics, where topics related with REST testing get the highest interest. Therefore I’ve decided to create some kind of example framework for RESTful APIs functional testing. Project is based on REST-Assured as a services client, Spock as a testing framework, Groovy and Gradle. You can clone full repository from my github. Tests are run against Wiremock API described in this post. Please consider this project as a kind of bootstrap, since it’s an example, not full-blown test framework. Ok, so as Linus said – talk is cheap, show me the code!
Dependencies Usually, first thing for me after importing new project is opening build.gradle (or pom.xml, in case of maven). In our example, the most important dependencies are REST-Assured and Spock. We’ve also Jackson, for serializing objects, Logback for our logs and snakeyaml for reading .yaml files,…