Many backend services need to integrate with other services via a number of protocols or API conventions.
Common ones are: REST, GraphQL, Queues, and gRPC.
Today, we're looking at how we can simplify microservice development by mocking external gRPC endpoints with GripMock.
Using GripMock is a simple 4-step process:
We start by creating a new folder: mkdir grpc-mock-server
.
Now, create a file with all the gRPC definitions you need. You can do this by copying over the gRPC files with the method definitions you need and removing everything you don't need.
Your should now have something like this:
// hello.proto
syntax = "proto3";
package auth;
option go_package = "github.com/simonme/article-examples/gripmock/hello;hello";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
Next up we need to define the value our mock server should return.
Create a stubs/hello-stub.json
file with the following content:
// stubs/hello-stub.json
{
"service": "Greeter",
"method": "SayHello",
"input": { "matches": { "name": ".*" } },
"output": { "data": { "message": "Hello mock user!" } }
}
Let's go through this:
service
we define the gRPC servicemethod
is the method name we want to stubinput
matching rule that tells GripMock when this stub should be usedoutput
of the gRPC methodIf we want to stub multiple methods, we simply create multiple *-stub.json
files.
Now run this command to start the server:
docker run --rm --name grpc-mock -p 4770:4770 -p 4771:4771 -v /Users/simon/projects/article-examples:/proto tkpd/gripmock --stub=/proto/stubs /proto/hello.proto
Let's break this up:
docker run --rm
run this image and remove the container afterwards--name grpc-mock
give this container a name-p 4770:4770 -p 4771:4771
map ports 4770 and 4771-v /Users/simon/projects/article-examples:/proto
add the article-examples folder (which contains the proto definition and stubs as a folder (/proto
) to the docker containertkpd/gripmock
which Docker image to use--stub=/proto/stubs
the stubs will be in the /proto/stubs
folder/proto/hello.proto
this defines the path to the relevant proto fileStarting the GripMock server can take a few seconds. You need to wait until you see Serving gRPC on …
in your console.
Starting GripMock
Serving stub admin on http://:4771
grpc server pid: 119
Serving gRPC on tcp://:4770
You can find out more about GripMock in their docs.
GripMock Q&A:
"input": { "matches": {} }
-d
flag to the docker command somewhere before tkpd/gripmock
to run it detachedIf you have any other questions (or answers) you can email them to me and I'll add them here.