1
func GetImagesList() {
   conn, err := grpc.Dial(address, grpc.WithInsecure())
   if err != nil {
      Log.Info("did not connect: %v", err)
   }

   defer conn.Close()

   // Get Client from the grpc connection
   client := pb.NewGrpcClient(conn)
   resp, err := client.GetImages(context.Background(), 
      &pb.ImageListRequest{})
 }

How to do mock GetImagesList GRPC method Please help me out. Thanks

Anupam Somani
  • 224
  • 1
  • 7
  • 17

1 Answers1

6

Part of your problem here is that the code that creates the client, is the code that you are trying to test with a mock.

Using an interface you can pass a mock into a method / function that you are trying to test. Step 1. would be splitting the code that creates the client, from the code where you want to inject the mock.

You should define an interface that you are trying to mock, it will allow you to swap the actual / real implementation for a fake / mock version, something like:

type ImagesGetter interface {
    func GetImages(ctx context.Context, in *pb.ImageListRequest) (*pb.ImageListResponse, error)
}

Then create a new struct type that will allow you to set the mock / real implementation.

type Lister struct {
    images ImagesGetter
}

func (l *Lister) GetImagesList() {

    // trimmed, but the grpc client should be defined 
    // and constructed outside this function and passed 
    // in in the images field of the Lister.

    resp, err := l.images.GetImages(ctx, &pb.GetImagesRequest)

    // trimmed ..
}

You can now construct the new Lister model with a mock implementation:

type mock struct {}

func (m *mock) GetImages(ctx context.Context, in *pb.ImageListRequest) (*pb.ImageListResponse, error) {
    // do mock implementation things here
}

And use it:

l := &Lister{images: &mock{}}
Zak
  • 5,515
  • 21
  • 33
  • 1
    How do we have client instantiated for unit tests without connection interface ? Unable to unit test similar scenario, where 1 RPC service method is invoking another RPC (2) method. And if we need to unit test RPC service 1 , RPC 2 mock client must be passed, but i am unable to implement such mock. i have tried gomock - it is working fine if we directly verify RPC2, however on RPC service 1, it returns an error , about no controller for this method exist. Though newbie in go, but i am leaning towards creating somethign like above instead of relying on mock frameworks, How do we do that? – nukul Jun 25 '20 at 00:52