1# Mocking Service for gRPC
2
3[Example code unary RPC](https://github.com/grpc/grpc-go/tree/master/examples/helloworld/mock_helloworld)
4
5[Example code streaming RPC](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/mock_routeguide)
6
7## Why?
8
9To test client-side logic without the overhead of connecting to a real server. Mocking enables users to write light-weight unit tests to check functionalities on client-side without invoking RPC calls to a server.
10
11## Idea: Mock the client stub that connects to the server.
12
13We use Gomock to mock the client interface (in the generated code) and programmatically set its methods to expect and return pre-determined values. This enables users to write tests around the client logic and use this mocked stub while making RPC calls.
14
15## How to use Gomock?
16
17Documentation on Gomock can be found [here](https://github.com/golang/mock).
18A quick reading of the documentation should enable users to follow the code below.
19
20Consider a gRPC service based on following proto file:
21
22```proto
23//helloworld.proto
24
25package helloworld;
26
27message HelloRequest {
28    string name = 1;
29}
30
31message HelloReply {
32    string name = 1;
33}
34
35service Greeter {
36    rpc SayHello (HelloRequest) returns (HelloReply) {}
37}
38```
39
40The generated file helloworld.pb.go will have a client interface for each service defined in the proto file. This interface will have methods corresponding to each rpc inside that service.
41
42```Go
43type GreeterClient interface {
44    SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)
45}
46```
47
48The generated code also contains a struct that implements this interface.
49
50```Go
51type greeterClient struct {
52   cc *grpc.ClientConn
53}
54func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error){
55    // ...
56    // gRPC specific code here
57    // ...
58}
59```
60
61Along with this the generated code has a method to create an instance of this struct.
62```Go
63func NewGreeterClient(cc *grpc.ClientConn) GreeterClient
64```
65
66The user code uses this function to create an instance of the struct greeterClient which then can be used to make rpc calls to the server.
67We will mock this interface GreeterClient and use an instance of that mock to make rpc calls. These calls instead of going to server will return pre-determined values.
68
69To create a mock we’ll use [mockgen](https://github.com/golang/mock#running-mockgen).
70From the directory ``` examples/helloworld/ ``` run ``` mockgen google.golang.org/grpc/examples/helloworld/helloworld GreeterClient > mock_helloworld/hw_mock.go ```
71
72Notice that in the above command we specify GreeterClient as the interface to be mocked.
73
74The user test code can import the package generated by mockgen along with library package gomock to write unit tests around client-side logic.
75```Go
76import "github.com/golang/mock/gomock"
77import hwmock "google.golang.org/grpc/examples/helloworld/mock_helloworld"
78```
79
80An instance of the mocked interface can be created as:
81```Go
82mockGreeterClient := hwmock.NewMockGreeterClient(ctrl)
83```
84This mocked object can be programmed to expect calls to its methods and return pre-determined values. For instance, we can program mockGreeterClient to expect a call to its method SayHello and return a HelloReply with message “Mocked RPC”.
85
86```Go
87mockGreeterClient.EXPECT().SayHello(
88    gomock.Any(), // expect any value for first parameter
89    gomock.Any(), // expect any value for second parameter
90).Return(&helloworld.HelloReply{Message: “Mocked RPC”}, nil)
91```
92
93gomock.Any() indicates that the parameter can have any value or type. We can indicate specific values for built-in types with gomock.Eq().
94However, if the test code needs to specify the parameter to have a proto message type, we can replace gomock.Any() with an instance of a struct that implements gomock.Matcher interface.
95
96```Go
97type rpcMsg struct {
98    msg proto.Message
99}
100
101func (r *rpcMsg) Matches(msg interface{}) bool {
102    m, ok := msg.(proto.Message)
103    if !ok {
104        return false
105    }
106    return proto.Equal(m, r.msg)
107}
108
109func (r *rpcMsg) String() string {
110    return fmt.Sprintf("is %s", r.msg)
111}
112
113...
114
115req := &helloworld.HelloRequest{Name: "unit_test"}
116mockGreeterClient.EXPECT().SayHello(
117    gomock.Any(),
118    &rpcMsg{msg: req},
119).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil)
120```
121
122## Mock streaming RPCs:
123
124For our example we consider the case of bi-directional streaming RPCs. Concretely, we'll write a test for RouteChat function from the route guide example to demonstrate how to write mocks for streams.
125
126RouteChat is a bi-directional streaming RPC, which means calling RouteChat returns a stream that can __Send__ and __Recv__ messages to  and from the server, respectively. We'll start by creating a mock of this stream interface returned by RouteChat and then we'll mock the client interface and set expectation on the method RouteChat to return our mocked stream.
127
128### Generating mocking code:
129Like before we'll use [mockgen](https://github.com/golang/mock#running-mockgen). From the `examples/route_guide` directory run:  `mockgen google.golang.org/grpc/examples/route_guide/routeguide RouteGuideClient,RouteGuide_RouteChatClient > mock_route_guide/rg_mock.go`
130
131Notice that we are mocking both client(`RouteGuideClient`) and stream(`RouteGuide_RouteChatClient`) interfaces here.
132
133This will create a file `rg_mock.go` under directory `mock_route_guide`. This file contains all the mocking code we need to write our test.
134
135In our test code, like before, we import the this mocking code along with the generated code
136
137```go
138import (
139    rgmock "google.golang.org/grpc/examples/route_guide/mock_routeguide"
140    rgpb "google.golang.org/grpc/examples/route_guide/routeguide"
141)
142```
143
144Now considering a test that takes the RouteGuide client object as a parameter, makes a RouteChat rpc call and sends a message on the resulting stream. Furthermore, this test expects to see the same message to be received on the stream.
145
146```go
147var msg = ...
148
149// Creates a RouteChat call and sends msg on it.
150// Checks if the received message was equal to msg.
151func testRouteChat(client rgb.RouteChatClient) error{
152    ...
153}
154```
155
156We can inject our mock in here by simply passing it as an argument to the method.
157
158Creating mock for stream interface:
159
160```go
161    stream := rgmock.NewMockRouteGuide_RouteChatClient(ctrl)
162}
163```
164
165Setting Expectations:
166
167```go
168    stream.EXPECT().Send(gomock.Any()).Return(nil)
169    stream.EXPECT().Recv().Return(msg, nil)
170```
171
172Creating mock for client interface:
173
174```go
175    rgclient := rgmock.NewMockRouteGuideClient(ctrl)
176```
177
178Setting Expectations:
179
180```go
181    rgclient.EXPECT().RouteChat(gomock.Any()).Return(stream, nil)
182```
183