如何使用Go接口测试Google API Golang lib?

时间:2015-02-13 11:24:58

标签: go google-drive-api

我尝试使用接口来测试使用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)

界面似乎只能在1级深度工作。

有人可以推荐一种替代方法来模拟这种依赖吗?

1 个答案:

答案 0 :(得分:0)

  

界面似乎只能在1级深度工作。

Go没有co / ntravariance的概念。 Get的签名与MyFilesService接口不兼容。正如您的错误消息告诉您:

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

有人可以推荐一种替代方法来模拟这种依赖吗?

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