首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >写下用于测试Go Mongo驱动程序的接口

写下用于测试Go Mongo驱动程序的接口
EN

Stack Overflow用户
提问于 2019-11-19 18:21:22
回答 1查看 265关注 0票数 2

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

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

代码语言:javascript
复制
type MongoChecksRunner struct {
    Client ClientHelper
}

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

代码语言:javascript
复制
type ClientHelper interface {
    Database(name string, opts ...*options.DatabaseOptions) DatabaseHelper
    Connect(ctx context.Context) error
}

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

代码语言:javascript
复制
type DatabaseHelper interface {
    RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) SingleResultHelper
}

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

代码语言:javascript
复制
type SingleResultHelper interface {
    Decode(v interface{}) error
    Err() error
}

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

代码语言:javascript
复制
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包结构的方法签名:

代码语言:javascript
复制
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

预先感谢您的任何帮助

EN

回答 1

Stack Overflow用户

发布于 2021-08-14 09:35:02

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58931684

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档