How To Mock A Kitex Client

Introduction

Sometimes, during testing, it may not be necessary to create an actual Kitex client. Instead, a mock client can be used as a stub object. This article will explain how to combine go mock to achieve this.

Usage

Installing go mock (mockgen)

go install go.uber.org/mock/mockgen@latest

For more details, please refer to: go mock

Using go mock

The mock approach for Kitex is as follows:

Locate the client in the kitex_gen directory, which contains the corresponding client interface. Use go mock to generate a mock client.

mockgen -source=kitex_gen/xxxx/xxxservice/client.go -destination=xxx/client_mock.go -package=xxx

This command will generate client_mock.go, which can be used in tests:

// Implement the mock methods you want for MockHello
func MockHello(ctx context.Context, req *hello.MyReq, callOptions ...callopt.Option) (*hello1.MyResp, error) {
   return &hello.MyResp{Message: "hello:" + req.Name}, nil
}

// Test the mock function for the client
func TestClient(t *testing.T) {
    
   ctrl := gomock.NewController(t)
   defer ctrl.Finish()

   // Get the client generated by go mock
   client := NewMockClient(ctrl)

   // Add the mock function
   client.EXPECT().Hello(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(MockHello).AnyTimes()
   
   // Make a mock call
   resp, err := client.Hello(context.Background(), &hello.MyReq{Name: "bd"})
   if err == nil {
      fmt.Println(resp.Message)
   } else {
      fmt.Println(err)
   }
}

Others

If you don’t want to use go mock or if you want to verify other capabilities of the client (such as tracing), you can also specify custom middleware when creating the client to construct data as needed.

Note: The built-in middleware of the Kitex client will still be executed.