登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-30 23:00:36 149浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《写下用于测试Go Mongo驱动程序的接口》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我正在尝试为一个使用 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
}

我收到以下错误:无法使用客户端(*mongo.client 类型的变量)作为结构文字中的 clienthelper 值: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

预先感谢您提供的任何帮助


解决方案


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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>