Part 2: Mocking a RESTful Microservice in MounteBank
In previous article I explained importance of mocking microservices. Now let’s have a look how MounteBank can help us to mock a microservice without writing any code.
What is MounteBank?
Mountebank is the first open source tool to provide cross-platform, multi-protocol test doubles over the wire. Simply point your application under test to mountebank instead of the real dependency, and test like you would with traditional stubs and mocks.
Basically it provides a server that can be configured using a DSL to simulate requests and responses over variety of protocols (http, https, tcp and smtp).
How it works?
There are various ways to install MounteBank on different platforms. We recommend to use via npm.
- Install npm
- Install MounteBank globally
$ npm mountebanck -g
$ mb –allowCORS –allowInjection –mock
By default it starts on the port 2525.
Now let’s learn some basic terminologies used by MounteBank DSL.
- Response - Defines status code, headers and body
- Predicate - Conditions to check request to match some criteria based on which response will be returned
- Stub - Also called Imposter is a Collection of predicates and responses for simulating an API
The DSL is very rich and we cannot cover everything here. For more details visit the API contract.
Now let us mock Get All Posts and Get a Specific Post API.
Get All Post
Here is a sample JSON to mock a RESTful service to get all posts,
This JSON is easy to understand. It defines an impostor (stub) for GET /posts API (using a predicate) listening at 9999 port to return a JSON (response) having two posts details.
Use this JSON and send it to MounteBank Server already running on your local machine.
It should create an impostor successfully and return same JSON as you sent in request.
Now go and hit http://localhost:9999/posts in REST Client or Browser and you should receive JSON having two posts data.
Get a Post
Similarly you can prepare impostor to get a single post.
Now hit http://localhost:9999/posts/1 in REST Client or Browser and you should receive JSON of the post.
Submit this JSON to MounteBank Server running locally. Then try sending mentioned JSON in above snippet to mapped URL.
Now it’s your turn. Create impostors for rest of the RESTful APIs and get hands on it.
At BoTree Technologies, we build enterprise apps with our web development team of 30+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management