How can I mock or simulate gRPC APIs?

Viewed 1316

I am doing a lot of manual exploratory testing of microservices after a feature story has been delivered. To do that, I need to simulate different responses from a gRPC API. So I would like to start a docker image with my microservice, and point it at a gRPC API that I can control and simulate different types of responses to test different sad-path scenarios.

How can I create mocks of gRPC APIs?

2 Answers

There are multiple tools available on GitHub. You can find related repositories using the corresponding grpc-mock topic link.

Another possible solution is to use a cloud solution such as mock.qa. Mock.qa is a cloud service (SaaS) that provides a production-ready gRPC mocking server and supports both gRPC and gRPC-web protocols. For example, the Greeter service with the following .proto file:

syntax = "proto3";

package demo.greet;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply);
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

can be mocked using the following mock.qa configuration file:

---
fileVersion: v1
serverName: Greet
protoFile: "/greet.proto"

# Incoming request matching is done in the order of definition,
# sequentially, from the first one to the last one,
# once match is found, the processing stops
calls: 

# First, we try to match a call to Joe
- method: SayHello
  request:
    body:
      Name: "Joe"
  response:
    body:
      Message: Hello Joe!
    status: OK

# Then, we try to match a call to Kelly
- method: SayHello
  request:
    body:
      Name: "Kelly"
  response:
    body:
      Message: Hello Kelly!
    status: OK

# And if no match, fall back to NotFound
- method: SayHello
  # "request" section is optional and may absent
  #   -  if "request" section is absent 
  #      then any call of the method is matched
  response:
    statusCode: NOT_FOUND
    statusDetails: Name not found
Related