mock server

Simplify Integration Testing with MockServer

1118 VIEWS

· · ·

At times you may stall development because you need to wrap your head around some API. At other times, you may pause simply because the API you need to connect with your frontend is simply not ready (or unavailable for other reasons). This happens quite often. It shouldn’t significantly slow down development, but it usually does.

Consider the following scenario. You’re working on a program which requires an API to perform an essential function. Unluckily, the API is not quite ready for use, as the team working on the API has a critical bug to fix before making it available. Obviously, this may delay development for some time. Ideally, you’d like to continue work despite this setback.

What if you could mimic the API you needed to continue with your development? Well—Great! That is exactly what a mock server does. A mock server mimics the behavior of a real web server. This has several benefits. An obvious one is that it will speed up development. Another is that a mock server comes in handy when testing. (Say, for example, that you want to recreate a special case that causes an error or you want to find out how changes to an API affect your application.) And, of course, you can work fully offline.

There are quite a number of mock servers. There’s an implementation for most languages, but you will often come across MockServer, WireMock, and JSON Server. I will only cover MockServer. (This should make it easy to use the others.)

Getting Started with MockServer

MockServer is used to mock systems that utilize HTTP or HTTPS. The concept is simple: You send a request, MockServer matches it with a configured expectation, and an action is taken. MockServer, in addition, provides a proxy for recording requests sent by a system.

Setup
One thing to love about MockServer is its support for many usage patterns: Node js module, Java package, command line, Homebrew package, Docker, Grunt plugin, and deployable WAR.

Node.js users should install the following: mockserver-node and mockserver-client. To use it, add this line to your project: require(‘mockserver-node’).

Docker

 docker pull jamesdbloom/mockserver

Java
I’ll cover how to use MockServer in Java. Get the JAR file and dependencies from Maven Central. The group ID is org.mock–server and the artifact ID is mockserver-netty.
Start the server and create a client for it. (Of course, you can create the two separately.)

 import org.mockserver.model.*;
import org.mockserver.integration.ClientAndServer;

ClientAndServer clientServer = ClientAndServer.startClientAndServer(2018);
         System.out.println(clientServer.isRunning());      //running status: true

// simple expectation for GET
         clientServer.when(new HttpRequest().withMethod("GET"))
                 .respond(new HttpResponse().withStatusCode(HttpStatusCode.OK_200.code())
                         .withBody("{'message': 'How may I help you?'}"));

// simple expectation for POST
clientServer.when(new HttpRequest().withMethod("POST").withPath("/start"))
                 .respond(new HttpResponse().withStatusCode(HttpStatusCode.ACCEPTED_202.code())
                         .withBody("Successful");

With the server running, a GET request to localhost:2018 should display the body with the key-value pair “message” and “How may I help you?” The POST request in the example responds to only the start endpoint, and the response body should be “Successful.”

An expectation contains a request matcher (method, header, path, body), an action (response, forward, error, or callback), times (number of times an action should be performed), and how long the expectation should stay alive. In case you want to mock a proxy, you’ll need to use ClientAndProxy and call its startClientAndProxy method.

The verify method of the ClientAndServer class exposes several constructs to verify requests such as the number of times a request has been made, and sequence of receipt.

With a little more tweaking, you should have a mock API to begin testing. To make it easier to work with JSON, you may want to add a Java library like Gson.

 Final Thoughts

At one point or another, you may need an API that may not be readily available. You should seriously consider using a mock server (custom-built or a third-party solution). A mock server will help you reduce API bills, as you can mock parts of paid APIs during testing and integrate with the paid version once you’re done, with a little tweaking afterwards. Your development cycle will be smoother with a mock server. Happy mocking!


Bruno is a junior at Ashesi University College studying Computer Science. He is interested in leveraging the power of technology to increase productivity. As a big fan of open source technology, he is currently exploring the possibility of using the Bitcoin Blockchain to fight corruption in government.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu