1

我刚刚学习了 Go 语言,然后使用https://github.com/mongodb/mongo-go-driver使用 MongoDB 和 Golang 制作休息 API,然后我正在做一个单元测试,但是在模拟 Cursor 时我被卡住了MongoDB,因为 Cursor 是一个结构,是一个想法还是有人做出来的?

4

2 回答 2

0

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

关于如何创建接口的示例

type Cursor interface{
  Next(ctx Context)
  Close(ctx Context)  
}

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

于 2019-09-28T07:54:13.183 回答
0

我刚刚遇到了这个问题。因为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随着时间的推移,我将不得不向界面添加新功能。

于 2020-09-13T08:42:45.330 回答