【问题标题】:Write down interfaces for testing the Go Mongo driver写下测试 Go Mongo 驱动的接口
【发布时间】:2020-03-14 19:59:56
【问题描述】:

我正在尝试为一个使用 golang mongo 驱动程序的新项目编写测试。遗憾的是他们没有使用接口,所以我基本上是在尝试自己写下我正在使用的几种方法,但可能在 Go 中遗漏了一些东西。

假设我有以下struct,它是存储库部分的根:

type MongoChecksRunner struct {
    Client ClientHelper
}

ClientHelper是原*mongo.Client实现的如下接口:

type ClientHelper interface {
    Database(name string, opts ...*options.DatabaseOptions) DatabaseHelper
    Connect(ctx context.Context) error
}

每一层都有接口,所以对于原来的*mongo.Database结构,我们得到:

type DatabaseHelper interface {
    RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) SingleResultHelper
}

最后,对于原始的*mongo.SingleResult 结构,我们有:

type SingleResultHelper interface {
    Decode(v interface{}) error
    Err() error
}

但是,当我尝试实例化一个新的MongoChecksRunner 时,它无法编译:

func NewMongoChecksRunner(host string, port int) (*MongoChecksRunner, error) {
    client, err := mdriver.NewClient(
        options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%d", host, port)),
        options.Client().SetDirect(true),
    )
    if err != nil {
        return nil, err
    }

    return &MongoChecksRunner{
        Client: client,
    }, nil
}

我收到以下错误:cannot use client (variable of type *mongo.Client) as ClientHelper value in struct literal: wrong type for method Database

Golang 是否有任何限制阻止您对接口进行多层嵌套?

请在下面找到原始 mongo 包结构的方法签名:

func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database
func (c *Client) Connect(ctx context.Context) error
func (db *Database) RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) *SingleResult
func (sr *SingleResult) Decode(v interface{}) error
func (sr *SingleResult) Err() error

提前感谢您的任何帮助

【问题讨论】:

  • 为了满足接口,方法必须匹配逐字Foo() DatabaseHelper不匹配Foo() *mongo.Database逐字*mongo.Database实现DatabaseHelper无关紧要,重要的是方法名和签名。
  • ... 因此,为了能够做您想做的事,您需要围绕实现编写包装器,并让这些包装器从接口实现方法返回正确的类型。
  • 类似这样的东西:stackoverflow.com/a/53823961/965900
  • 感谢您的回答,对我帮助很大。我觉得有点失望,但至少我现在知道该怎么做了!

标签: mongodb unit-testing go


【解决方案1】:

使用https://pkg.go.dev/github.com/256dpi/lungo模拟Mongo驱动并拥有通用接口

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    相关资源
    最近更新 更多