登录
首页 >  Golang >  Go问答

如何使用 mongo-go-driver 模拟光标

来源:stackoverflow

时间:2024-04-03 15:18:32 160浏览 收藏

你在学习Golang相关的知识吗?本文《如何使用 mongo-go-driver 模拟光标》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我刚刚学习了 go 语言,然后使用 https://github.com/mongodb/mongo-go-driver 与 MongoDB 和 Golang 一起制作 REST API,然后我正在进行单元测试,但我陷入了困境当嘲笑 Cursor MongoDB 时,因为 Cursor 是一个结构,是一个想法还是有人创造了它?


解决方案


在我看来,模拟此类对象的最佳方法是定义一个接口,因为 go 接口是隐式实现的,您的代码可能不需要那么多更改。一旦你有了一个界面,你就可以使用一些第三方库来自动生成模拟,比如 mockery

如何创建界面的示例

type cursor interface{
  next(ctx context)
  close(ctx context)  
}

只需更改接收 mongodb 游标的任何函数即可使用自定义接口

我刚刚遇到了这个问题。因为 mongo.cursor 有一个内部字段保存 []byte -- current,为了完全模拟,您需要包装 mongo.cursor。以下是我为此创建的类型:

type MongoCollection interface {
    Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (MongoCursor, error)
    FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) MongoDecoder
    Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (MongoCursor, error)
}

type MongoDecoder interface {
    DecodeBytes() (bson.Raw, error)
    Decode(val interface{}) error
    Err() error
}

type MongoCursor interface {
    Decode(val interface{}) error
    Err() error
    Next(ctx context.Context) bool
    Close(ctx context.Context) error
    ID() int64
    Current() bson.Raw
}

type mongoCursor struct {
    mongo.Cursor
}

func (m *mongoCursor) Current() bson.Raw {
    return m.Cursor.Current
}

不幸的是,这将是一个移动目标。随着时间的推移,我必须向 mongocollection 接口添加新函数。

好了,本文到此结束,带大家了解了《如何使用 mongo-go-driver 模拟光标》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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