![](/img/trans.png)
[英]Deserialize cursor into array with mongo-go-driver and interface
[英]How to mock cursor with mongo-go-driver
I just learned go language, and then used https://github.com/mongodb/mongo-go-driver for make rest API with MongoDB and Golang and then I'm doing a unit test, but I'm stuck when mocking Cursor MongoDB,因为 Cursor 是一个结构,这是一个想法还是有人做出来的?
在我看来,mocking 这种对象的最佳方法是定义一个接口,因为在 go 接口是隐式实现的,您的代码可能不需要那么多更改。 一旦你有了一个接口,你就可以使用一些第三方库来自动生成模拟,比如模拟
关于如何创建接口的示例
type Cursor interface{
Next(ctx Context)
Close(ctx Context)
}
只需更改接收 mongodb cursor 的任何 function 以使用自定义接口
我刚刚遇到了这个问题。 因为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
接口添加新功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.