1. 程式人生 > >[Go][gRPC]mock初體驗

[Go][gRPC]mock初體驗

pic test ogl fin stc eth inf ctx return

方法1:使用monkey包,直接對pb.go裏面的方法進行mock

 1 package assetengine
 2 
 3 import (
 4     "context"
 5     "fmt"
 6     "reflect"
 7 
 8     "bou.ke/monkey"
 9     //"golang.org/x/net/context"
10     "google.golang.org/grpc"
11 )
12 
13 func AddMonkey() {
14     var c *apiClient
15 
16     add := monkey.PatchInstanceMethod(reflect.TypeOf(c),
17 "AddItemQuantity", 18 func(_ *apiClient, ctx context.Context, in *AddItemQuantityRequest, opts ...grpc.CallOption) (*AddItemQuantityReply, error) { 19 fmt.Printf("mock AddItemQuantity start \n") 20 rs := Result{Code: ERROR_SHIELD_REJECT, Info: "mock result"}
21 // fmt.Printf %v : 以更好的格式輸出 22 fmt.Printf("AddItemQuantity v %v \n", rs) // AddItemQuantity v {SHIELD_REJECT mock result} 23 // fmt.Printf %#v :直接輸出錯誤碼 24 fmt.Printf("AddItemQuantity resp code %#v \n", rs) //AddItemQuantity resp code assetengine.Result{Code:402, Info:"mock result"}
25 // 只輸出錯誤描述 26 fmt.Printf("只輸出錯誤描述 %v \n", rs.Code) // 只輸出錯誤描述 SHIELD_REJECT 27 // 只輸出錯誤碼 28 fmt.Printf("justcode %#v \n", rs.Code) // justcode 402 29 return &AddItemQuantityReply{&rs}, nil 30 }) 31 fmt.Printf("add %#v\n", add) 32 33 }

調用方式:

1 func Test_mock_adduservas(t *testing.T) {
2     pb.AddMonkey()
3     c := pb.NewApiClient(nil)
4     res, _ := c.AddItemQuantity(context.Background(), &pb.AddItemQuantityRequest{})
5     fmt.Printf("test resp %#v \n", res.Result)
6 
7 }

方法2:使用gomock工具對.proto文件進行mock,生成mock代碼

命令:mockgen -source sourcefilename.go > targetfilename.go

生成mock代碼後調用如下:

 1 package mock_assetengine
 2 
 3 import (
 4     "context"
 5     "testing"
 6 
 7     "github.com/golang/mock/gomock"
 8 )
 9 
10 func Test_mockgrpc(t *testing.T) {
11 
12     res := Result{
13         Code: ERROR_SHIELD_REJECT,
14         Info: "mock result",
15     }
16     ctrl := gomock.NewController(t)
17     defer ctrl.Finish()
18 
19     // 這裏mock的是 ApiClient 和 ApiServer
20     // 在mock文件裏分別對應
21     // ApiClient -> NewMockApiClient
22     // ApiServer -> NewMockApiServer
23     // 查找備註 creates a new mock instance
24     mockApiClient := NewMockApiClient(ctrl)
25     mockApiClient.EXPECT().AddItemQuantity(
26         gomock.Any(),
27         gomock.Any(),
28     ).Return(&AddItemQuantityReply{&res}, nil)
29     testMock(t, mockApiClient)
30 }
31 
32 func testMock(t *testing.T, client ApiClient) {
33     t.Helper()
34     resp, _ := client.AddItemQuantity(context.Background(), &AddItemQuantityRequest{})
35     t.Log("Reply : ", resp)
36 }

運行結果:

技術分享圖片

[Go][gRPC]mock初體驗