如何在Golang中模拟GCP的存储?

问题描述 投票:0回答:1

我真的很擅长嘲笑第三方库,我现在正在嘲笑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

但是,我收到了这个错误:

无法使用客户端(键入*“cloud.google.com/go/storage”.Client)作为字段值类型stiface.Client:*“cloud.google.com/go/storage”.Client未实现stiface.Client( Bucket方法的错误类型)有Bucket(string)*“cloud.google.com/go/storage”.BucketHandle想要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
}
go mocking
1个回答
1
投票

错误消息基本上是说你的stiface.Client定义了*storage.Client没有实现的接口。乍一看,您的代码看起来有效,但问题出在您的接口方法签名上,因为它们有输出作为接口。

Go在语句之间有所不同:

  • 此函数返回BucketHandle
  • 并且此函数返回*storage.BucketHandle,这是一个BucketHandle

尝试更改界面以返回*storage.BucketHandle。您可以在mockery S3API example中看到更复杂的类似行为示例,其中函数返回s3类型,而不是它们自己的接口。

© www.soinside.com 2019 - 2024. All rights reserved.