猿问

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

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



海绵宝宝撒
浏览 211回答 2
2回答

aluckdog

在我看来,模拟此类对象的最佳方法是定义一个接口,因为 go 接口是隐式实现的,您的代码可能不需要那么多更改。一旦你有了一个界面,你就可以使用一些第三方库来自动生成模拟,比如嘲笑有关如何创建界面的示例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随着时间的推移,我将不得不向界面添加新功能。
随时随地看视频慕课网APP

相关分类

Go
我要回答