github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/mocking/README.md (about)

     1  # Mocking
     2  
     3  Thie example demonstrates how to mock the helloworld service
     4  
     5  The generated protos create a `Service` interface used by the client. This can simply be mocked.
     6  
     7  ```go
     8  type GreeterService interface {
     9  	Hello(ctx context.Context, in *Request, opts ...client.CallOption) (*Response, error)
    10  }
    11  ```
    12  
    13  Where the `GreeterService` is used we can instead pass in the mock which returns the expected response rather than calling a service.
    14  
    15  ## Mock Client
    16  
    17  ```go
    18  type mockGreeterService struct {
    19  }
    20  
    21  func (m *mockGreeterService) Hello(ctx context.Context, req *proto.Request, opts ...client.CallOption) (*proto.Response, error) {
    22          return &proto.Response{
    23                  Greeting: "Hello " + req.Name,
    24          }, nil
    25  }
    26  
    27  func NewGreeterService() proto.GreeterService {
    28          return new(mockGreeterService)
    29  }
    30  ```
    31  
    32  ## Use Mock
    33  
    34  In the test environment we will use the mock client
    35  
    36  ```go
    37  func main() {
    38  	var c proto.GreeterService
    39  
    40  	service := micro.NewService(
    41  		micro.Flags(&cli.StringFlag{
    42  			Name: "environment",
    43  			Value: "testing",
    44  		}),
    45  	)
    46  
    47  	service.Init(
    48  		micro.Action(func(ctx *cli.Context) error {
    49  			env := ctx.String("environment")
    50  			// use the mock when in testing environment
    51  			if env == "testing" {
    52  				c = mock.NewGreeterService()
    53  			} else {
    54  				c = proto.NewGreeterService("helloworld", service.Client())
    55  			}
    56                          return nil
    57  		}),
    58  	)
    59  
    60  	// call hello service
    61  	rsp, err := c.Hello(context.TODO(), &proto.Request{
    62  		Name: "John",
    63  	})
    64  	if err != nil {
    65  		fmt.Println(err)
    66  		return
    67  	}
    68  	fmt.Println(rsp.Greeting)
    69  }
    70  ```