go-micro examples 中mocking 代码学习(为方面分工开发 或测试 mock调用微服务)

对应 examples/mocking 例子

这个例子 展示 了 如何 mock 调用 微服务。

目录如下:

go-micro examples 中mocking 代码学习(为方面分工开发 或测试 mock调用微服务)_第1张图片

helloworld  :  helloworld 微服务,(可假设下这是由项目中其他人开发,维护,我们只是调用)

helloworld/proto/greeter.proto 代码如下:

syntax = "proto3";

service Greeter {
    rpc Hello(HelloRequest) returns (HelloResponse) {}
}

message HelloRequest {
    string name = 1;
}

message HelloResponse {
    string greeting = 2;
}

helloworld/main.go 代码如下:

package main

import (
	"context"
	"github.com/micro/go-micro"
	"log"
	proto "mocking/helloworld/proto"
)

type Greeter struct{}

func (g *Greeter) Hello(ctx context.Context, req *proto.HelloRequest, rsp *proto.HelloResponse) error {
	rsp.Greeting = "Hello " + req.Name

	return nil
}

func main() {
	service := micro.NewService(
		micro.Name("helloworld"),
	)

	service.Init()

	proto.RegisterGreeterHandler(service.Server(), new(Greeter))

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}

mock/mock.go 代码如下:

package mock

import (
	"context"
	"github.com/micro/go-micro/client"
	proto "mocking/helloworld/proto"
)

type mockGreeterService struct{}

func (m *mockGreeterService) Hello(ctx context.Context, req *proto.HelloRequest, opts ...client.CallOption) (*proto.HelloResponse, error) {
	return &proto.HelloResponse{
		Greeting: "Hello test ::" + req.Name,
	}, nil
}

func NewGreeterService() proto.GreeterService {
	return new(mockGreeterService)
}

main.go  代码如下 (rpc client)

package main

import (
	"context"
	"fmt"
	"github.com/micro/cli"
	"github.com/micro/go-micro"
	proto "mocking/helloworld/proto"
	"mocking/mock"
)

func main() {
	var c proto.GreeterService

	service := micro.NewService(
		micro.Flags(cli.StringFlag{
			Name:  "environment",
			//Value: "testing",
			Value: "",
		}),
	)

	service.Init(
		micro.Action(func(ctx *cli.Context) {
			env := ctx.String("environment")

			//在 测试环境中 使用 mock
			if env == "testing" {
				c = mock.NewGreeterService()
			} else {
				c = proto.NewGreeterService("helloworld", service.Client())
			}
		}),
	)

	//调用 hello service
	rsp, err := c.Hello(context.TODO(), &proto.HelloRequest{
		Name: "John",
	})

	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(rsp.Greeting)
}

go.mod 内容如下:

module mocking

go 1.13

require (
	github.com/golang/protobuf v1.3.2
	github.com/micro/go-micro v1.18.0
)

运行:

运行 helloworld 微服务

go run helloworld/main.go

bogon:mocking zhaozhiliang$ go run main.go --environment testing

Hello test ::John

bogon:mocking zhaozhiliang$ go run main.go

Hello John

 

 

你可能感兴趣的:(go语言)