我真的不熟悉在 go 中模拟第三方库,我现在正在模拟 cloud.google.com/go/storage
我正在使用 mockery .这是我当前的界面:
//Client storage client
type Client interface {
Bucket(name string) BucketHandle
Buckets(ctx context.Context, projectID string) BucketIterator
}
//BucketHandle storage's BucketHandle
type BucketHandle interface {
Attrs(context.Context) (*storage.BucketAttrs, error)
Objects(context.Context, *storage.Query) ObjectIterator
}
//ObjectIterator storage's ObjectIterator
type ObjectIterator interface {
Next() (*storage.ObjectAttrs, error)
}
//BucketIterator storage's BucketIterator
type BucketIterator interface {
Next() (*storage.BucketAttrs, error)
}
这就是我在我的函数中使用它的方式
//Runner runner for this module
type Runner struct {
StorageClient stiface.Client
}
.... function
//get storage client
client, err := storage.NewClient(ctx)
if err != nil {
return err
}
runner := Runner{
StorageClient: client,
}
.... rest of functions
但是,我得到了这个错误:
cannot use client (type *"cloud.google.com/go/storage".Client) as type stiface.Client in field value: *"cloud.google.com/go/storage".Client does not implement stiface.Client (wrong type for Bucket method) have Bucket(string) *"cloud.google.com/go/storage".BucketHandle want Bucket(string) stiface.BucketHandle
我做错了什么?谢谢!
编辑
这是我要模拟的代码示例之一。我想模拟 bucketIterator.Next()
:
//GetBuckets get list of buckets
func GetBuckets(ctx context.Context, client *storage.Client, projectName string) []checker.Resource {
//Get bucket iterator based on a project
bucketIterator := client.Buckets(ctx, projectName)
//iterate over the buckets and store bucket details
buckets := make([]checker.Resource, 0)
for bucket, done := bucketIterator.Next(); done == nil; bucket, done = bucketIterator.Next() {
buckets = append(buckets, checker.Resource{
Name: bucket.Name,
Type: "Bucket",
})
}
return buckets
}
最佳答案
错误消息基本上是说您的 stiface.Client
定义了 *storage.Client
未实现的接口(interface)。乍一看,您的代码看起来是有效的,但问题在于您的接口(interface)方法签名,因为它们将输出作为接口(interface)。
Go 对语句进行了区分:
- 这个函数返回一个
BucketHandle
- 并且此函数返回一个
*storage.BucketHandle
,它是一个BucketHandle
尝试更改您的接口(interface)以返回 *storage.BucketHandle
。您可以在 mockery S3API
example 中看到类似行为的更复杂示例。其中函数返回 s3
类型,而不是它们自己的接口(interface)。
关于go - 如何在 golang 中模拟 GCP 的存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55859268/