-
Notifications
You must be signed in to change notification settings - Fork 4.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Example code and documentation on how to mock gRPC services #1021
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9cc4fd4
Example code on how to mock gRPC services
MakMukhi 0708983
Create gomock-example.md
MakMukhi e6b4662
Update gomock-example.md
MakMukhi 5202729
Update gomock-example.md
MakMukhi 54f3001
Update gomock-example.md
MakMukhi a0474a6
exclude mockgen generated code from golint
MakMukhi 1a9e782
Merge branch 'mmukhi_gomock_example' of https://github.com/MakMukhi/g…
MakMukhi 6a68fd8
post review updates
MakMukhi 541319e
Update gomock-example.md
MakMukhi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
# Mocking Service for gRPC | ||
|
||
[Example code](https://github.com/grpc/grpc-go/tree/master/examples/helloworld/mock) | ||
|
||
## Why? | ||
|
||
To 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. | ||
|
||
## Idea: Mock the client stub that connects to the server. | ||
|
||
We 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. | ||
|
||
## How to use Gomock? | ||
|
||
Documentation on Gomock can be found [here](https://github.com/golang/mock). | ||
A quick reading of the documentation should enable users to follow the code below. | ||
|
||
Consider a gRPC service based on following proto file: | ||
|
||
```proto | ||
//helloworld.proto | ||
|
||
package helloworld; | ||
|
||
message HelloRequest { | ||
string name = 1; | ||
} | ||
|
||
message HelloReply { | ||
string name = 1; | ||
} | ||
|
||
service Greeter { | ||
rpc SayHello (HelloRequest) returns (HelloReply) {} | ||
} | ||
``` | ||
|
||
The 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. | ||
|
||
```Go | ||
type GreeterClient interface { | ||
SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) | ||
} | ||
``` | ||
|
||
The generated code also contains a struct that implements this interface. | ||
|
||
```Go | ||
type greeterClient struct { | ||
cc *grpc.ClientConn | ||
} | ||
func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error){ | ||
// ... | ||
// gRPC specific code here | ||
// ... | ||
} | ||
``` | ||
|
||
Along with this the generated code has a method to create an instance of this struct. | ||
```Go | ||
func NewGreeterClient(cc *grpc.ClientConn) GreeterClient | ||
``` | ||
|
||
The 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. | ||
We 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. | ||
|
||
To create a mock we’ll use [mockgen](https://github.com/golang/mock#running-mockgen). | ||
From the directory ``` examples/helloworld/mock/ ``` run ``` mockgen google.golang.org/grpc/examples/helloworld/helloworld GreeterClient > mock_helloworld/hw_mock.go ``` | ||
|
||
Notice that in the above command we specify GreeterClient as the interface to be mocked. | ||
|
||
The user test code can import the package generated by mockgen along with library package gomock to write unit tests around client-side logic. | ||
```Go | ||
import "github.com/golang/mock/gomock" | ||
import hwmock "google.golang.org/grpc/examples/helloworld/mock/mock_helloworld" | ||
``` | ||
|
||
An instance of the mocked interface can be created as: | ||
```Go | ||
mockGreeterClient := hwmock.NewMockGreeterClient(ctrl) | ||
``` | ||
This 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”. | ||
|
||
```Go | ||
mockGreeterClient.EXPECT().SayHello( | ||
gomock.Any(), // expect any value for first parameter | ||
gomock.Any(), // expect any value for second parameter | ||
).Return(&helloworld.HelloReply{Message: “Mocked RPC”}, nil) | ||
``` | ||
|
||
gomock.Any() indicates that the parameter can have any value or type. We can indicate specific values for built-in types with gomock.Eq(). | ||
However, 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. | ||
|
||
```Go | ||
type rpcMsg struct { | ||
msg proto.Message | ||
} | ||
|
||
func (r *rpcMsg) Matches(msg interface{}) bool { | ||
m, ok := msg.(proto.Message) | ||
if !ok { | ||
return false | ||
} | ||
return proto.Equal(m, r.msg) | ||
} | ||
|
||
func (r *rpcMsg) String() string { | ||
return fmt.Sprintf("is %s", r.msg) | ||
} | ||
|
||
... | ||
|
||
req := &helloworld.HelloRequest{Name: "unit_test"} | ||
mockGreeterClient.EXPECT().SayHello( | ||
gomock.Any(), | ||
&rpcMsg{msg: req}, | ||
).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil) | ||
``` | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package mock | ||
|
||
import ( | ||
"fmt" | ||
"testing" | ||
|
||
"github.com/golang/mock/gomock" | ||
"github.com/golang/protobuf/proto" | ||
"golang.org/x/net/context" | ||
helloworld "google.golang.org/grpc/examples/helloworld/helloworld" | ||
hwmock "google.golang.org/grpc/examples/helloworld/mock/mock_helloworld" | ||
) | ||
|
||
// rpcMsg implements the gomock.Matcher interface | ||
type rpcMsg struct { | ||
msg proto.Message | ||
} | ||
|
||
func (r *rpcMsg) Matches(msg interface{}) bool { | ||
m, ok := msg.(proto.Message) | ||
if !ok { | ||
return false | ||
} | ||
return proto.Equal(m, r.msg) | ||
} | ||
|
||
func (r *rpcMsg) String() string { | ||
return fmt.Sprintf("is %s", r.msg) | ||
} | ||
|
||
func TestSayHello(t *testing.T) { | ||
ctrl := gomock.NewController(t) | ||
defer ctrl.Finish() | ||
mockGreeterClient := hwmock.NewMockGreeterClient(ctrl) | ||
req := &helloworld.HelloRequest{Name: "unit_test"} | ||
mockGreeterClient.EXPECT().SayHello( | ||
gomock.Any(), | ||
&rpcMsg{msg: req}, | ||
).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil) | ||
testSayHello(t, mockGreeterClient) | ||
} | ||
|
||
func testSayHello(t *testing.T, client helloworld.GreeterClient) { | ||
r, err := client.SayHello(context.Background(), &helloworld.HelloRequest{Name: "unit_test"}) | ||
if err != nil || r.Message != "Mocked Interface" { | ||
t.Errorf("mocking failed") | ||
} | ||
t.Log("Reply : ", r.Message) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
// Automatically generated by MockGen. DO NOT EDIT! | ||
// Source: google.golang.org/grpc/examples/helloworld/helloworld (interfaces: GreeterClient) | ||
|
||
package mock_helloworld | ||
|
||
import ( | ||
gomock "github.com/golang/mock/gomock" | ||
context "golang.org/x/net/context" | ||
grpc "google.golang.org/grpc" | ||
helloworld "google.golang.org/grpc/examples/helloworld/helloworld" | ||
) | ||
|
||
// Mock of GreeterClient interface | ||
type MockGreeterClient struct { | ||
ctrl *gomock.Controller | ||
recorder *_MockGreeterClientRecorder | ||
} | ||
|
||
// Recorder for MockGreeterClient (not exported) | ||
type _MockGreeterClientRecorder struct { | ||
mock *MockGreeterClient | ||
} | ||
|
||
func NewMockGreeterClient(ctrl *gomock.Controller) *MockGreeterClient { | ||
mock := &MockGreeterClient{ctrl: ctrl} | ||
mock.recorder = &_MockGreeterClientRecorder{mock} | ||
return mock | ||
} | ||
|
||
func (_m *MockGreeterClient) EXPECT() *_MockGreeterClientRecorder { | ||
return _m.recorder | ||
} | ||
|
||
func (_m *MockGreeterClient) SayHello(_param0 context.Context, _param1 *helloworld.HelloRequest, _param2 ...grpc.CallOption) (*helloworld.HelloReply, error) { | ||
_s := []interface{}{_param0, _param1} | ||
for _, _x := range _param2 { | ||
_s = append(_s, _x) | ||
} | ||
ret := _m.ctrl.Call(_m, "SayHello", _s...) | ||
ret0, _ := ret[0].(*helloworld.HelloReply) | ||
ret1, _ := ret[1].(error) | ||
return ret0, ret1 | ||
} | ||
|
||
func (_mr *_MockGreeterClientRecorder) SayHello(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { | ||
_s := append([]interface{}{arg0, arg1}, arg2...) | ||
return _mr.mock.ctrl.RecordCall(_mr.mock, "SayHello", _s...) | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wrap this in a function
createMock
returning a mocking client?