go - 如何使用 Go 接口(interface)来测试 Google API Golang 库?

标签 go google-drive-api

我正在尝试使用接口(interface)来测试使用 google's drive api lib 的代码.

type MyFile struct {
  DownloadUrl string `json:"downloadUrl,omitempty"`
}

type MyFilesGetCall interface {
  Do() (*MyFile, error)
  // Do() (*drive.File, error) // this DOES work
}

type MyFilesService interface {
  Get(string) *MyFilesGetCall
  // Get(string) *drive.FilesGetCall // this DOES work
}

func GetInfo(id string, myService MyFilesService) {
  myService.Get(id).Do()
}

func main() {
  drive, _ := drive.New(new(http.Client))
  GetInfo("id", drive.Files)
}

当我尝试运行它时,出现以下错误:

$ go run so.go
./so.go:24: cannot use drive.Files (type *drive.FilesService) as type MyFilesService in argument to GetInfo:
        *drive.FilesService does not implement MyFilesService (wrong type for Get method)
                have Get(string) *drive.FilesGetCall
                want Get(string) *MyFilesGetCall
./so.go:28: fService.Get(id).Do undefined (type *MyFilesGetCall has no field or method Do)

接口(interface)似乎只能在 1 层深度工作。

谁能推荐一种替代方法来模拟这种依赖性?

最佳答案

It seems that interfaces only work 1 level deep.

Go 没有协变/协变的概念。 Get 的签名与 MyFilesService 接口(interface)不兼容。正如您的错误消息告诉您的那样:

*drive.FilesService does not implement MyFilesService (wrong type for Get method)
    have Get(string) *drive.FilesGetCall
    want Get(string) *MyFilesGetCall

Can anyone recommend an alternative approach for mocking this dependency?

MyFilesService 更改为 *drive.FilesService 实际实现的内容。

关于go - 如何使用 Go 接口(interface)来测试 Google API Golang 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28498527/

相关文章:

Golang 模块使用

go - 包命名 : error exporting variable

c# - 如果浏览器关闭,GoogleWebAuthorizationBroker.AuthorizeAsync() 会挂起

java - 使用 Google Drive API 时不显示上传的文件

google-apps-script - 高级驱动器服务在插入文件时返回空响应错误

opengl - Go-GL 中的曲面分割

go - 如何从接口(interface)中提取具体结构

go - Golang 中的泛型方法参数

android - 将应用程序数据高效同步到 Google Drive 中的应用程序文件夹

python - 使用 python 中的 api 将图像从驱动器插入幻灯片