我正在尝试使用接口(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/