dqxhit3376 2015-02-13 11:24
浏览 204

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

I'm trying to use interfaces to test code that uses 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)
}

When I try to run this I get the following error:

$ 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)

It seems that interfaces only work 1 level deep.

Can anyone recommend an alternative approach for mocking this dependency?

  • 写回答

1条回答 默认 最新

  • duan2891 2015-02-13 13:30
    关注

    It seems that interfaces only work 1 level deep.

    Go has no notion of co/ntravariance. The signature for Get is incompatible with the MyFilesService interface. As your error message told you:

    *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?

    Change MyFilesService to something that *drive.FilesService actually implements.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器