【发布时间】:2019-09-28 05:14:37
【问题描述】:
我刚刚学习了 Go 语言,然后使用 https://github.com/mongodb/mongo-go-driver 与 MongoDB 和 Golang 进行了 make rest API,然后我正在做一个单元测试,但是在模拟 Cursor MongoDB 时我被卡住了,因为 Cursor 是一个结构,一个有这个想法还是有人做到了?
【问题讨论】:
我刚刚学习了 Go 语言,然后使用 https://github.com/mongodb/mongo-go-driver 与 MongoDB 和 Golang 进行了 make 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 接口添加新功能。
【讨论】: