Mock server

20/09/2019

Mocking is widely used in the software development for testing, when tested piece of logic A invokes another piece of logic B, where behavior of B is irrelevant to the test (not the target of the test), so behavior of B needed to always return certain result, therefore behavior of B can be simulated (or mocked). This is where mocking comes into the game.

For example, you are writing a service which returns a list of items, each item is permission checked inside the service. Permission check is a call to an external interface (e.g. REST API). In this case, for testing purposes, it makes sense to mimic (or mock) response of permission check in order to get reproducible test case.

One of the ways for mocking said behavior is in app mocking with. There is a number of libraries for in app mocking, such as Mockito in Java or gomock in Go. Today I’ll focus on another approach, which relies on having standalone process running a mock server.

For the specific use case of mocking REST API - is a viable approach. It provides fairly universal and less intrusive (for tested system) way of mocking HTTP responses. It requires re-targeting of a client in the tested system to the mock server and this is pretty much it. This saves developer’s time, which would have been spent onto adding and learning mocking library. There is a disadvantage - it is a need in spinning up separate server every time test is being executed. So the easier and faster this “spin up” the better.

Today I’ve created a mock server, it can be found at github.com/smeshkov/gomock. It is easy to spin up, no extra setup is required for a development environment. Mock server is an executable binary, to have it up and running you need to execute ./gomock in your terminal, this is it. Mock server is configured with a JSON file, defaukt name for the file is mock.json, though it can be changed via -mock option, e.g. ./gomock -mock <name>.json. JSON file allows to set paths, HTTP methods, response statuses, delays and of course response payloads for mocks.

Happy mocking. Cheers.