标签:addm import star 方法 return tar org nis wapi
方法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 }
运行结果:
标签:addm import star 方法 return tar org nis wapi
原文地址:https://www.cnblogs.com/jiayoupaofu/p/9640636.html