Mongodb 如何使用mongo go驱动程序模拟光标
我刚刚学习了go语言,然后用MongoDB和Golang来制作rest API,然后我在做一个单元测试,但是我在模拟Cursor MongoDB时被卡住了,因为Cursor是一个结构,一个想法,或者是有人做的?在我看来,模拟这类对象的最好方法是定义一个接口,由于in-go接口是隐式实现的,您的代码可能不需要太多更改。一旦你有了一个界面,你就可以使用一些第三方库来自动生成模拟,比如 关于如何创建接口的示例Mongodb 如何使用mongo go驱动程序模拟光标,mongodb,go,mongo-go,Mongodb,Go,Mongo Go,我刚刚学习了go语言,然后用MongoDB和Golang来制作rest API,然后我在做一个单元测试,但是我在模拟Cursor MongoDB时被卡住了,因为Cursor是一个结构,一个想法,或者是有人做的?在我看来,模拟这类对象的最好方法是定义一个接口,由于in-go接口是隐式实现的,您的代码可能不需要太多更改。一旦你有了一个界面,你就可以使用一些第三方库来自动生成模拟,比如 关于如何创建接口的示例 type Cursor interface{ Next(ctx Context) C
type Cursor interface{
Next(ctx Context)
Close(ctx Context)
}
只要更改任何接收mongodb游标的函数以使用自定义接口在我看来,模拟此类对象的最佳方法是定义一个接口,因为在go中,接口是隐式实现的,您的代码可能不需要太多更改。一旦你有了一个界面,你就可以使用一些第三方库来自动生成模拟,比如
type Cursor interface{
Next(ctx Context)
Close(ctx Context)
}
关于如何创建接口的示例
type Cursor interface{
Next(ctx Context)
Close(ctx Context)
}
只需将任何接收mongodb游标的函数更改为使用自定义接口即可我刚刚遇到了这个问题。因为
mongo.Cursor
有一个内部字段,其中包含[]字节
--当前
,为了完全模拟,您需要包装mongo.Cursor
。以下是我为此制作的类型:
type Cursor interface{
Next(ctx Context)
Close(ctx Context)
}
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.Cursor
有一个内部字段,其中包含[]字节
--当前
,为了完全模拟,您需要包装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
界面添加新函数。如何提取值?如何提取值?