您的问题的一部分是创建客户端的代码是您尝试使用模拟测试的代码。
使用接口,您可以将模拟传递给您尝试测试的方法/函数。步骤 1. 将从要注入模拟的代码中拆分创建客户端的代码。
您应该定义一个您尝试模拟的接口,它将允许您将实际/真实实现交换为假/模拟版本,例如:
type ImagesGetter interface {
func GetImages(ctx context.Context, in *pb.ImageListRequest) (*pb.ImageListResponse, error)
}
然后创建一个新的结构类型,允许您设置模拟/真实实现。
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 ..
}
您现在可以Lister
使用模拟实现构建新模型:
type mock struct {}
func (m *mock) GetImages(ctx context.Context, in *pb.ImageListRequest) (*pb.ImageListResponse, error) {
// do mock implementation things here
}
并使用它:
l := &Lister{images: &mock{}}