繁体   English   中英

编写测试Go Mongo驱动的接口

[英]Write down interfaces for testing the Go Mongo driver

我正在尝试为使用 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 package 结构的方法签名:

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

预先感谢您的任何帮助

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM