简体   繁体   English

如何使用 mongo-go-driver 模拟 cursor

[英]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, because Cursor is a struct, an idea for that or someone made it? 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 是一个结构,这是一个想法还是有人做出来的?

In my opinion, the best approach to mocking this kind of objects is by defining an interface, as in go interfaces are implemented implicitly your code probably wouldn't need that much changes.在我看来,mocking 这种对象的最佳方法是定义一个接口,因为在 go 接口是隐式实现的,您的代码可能不需要那么多更改。 Once you have an interface you can use some third party library to autogenerate mocks, like mockery一旦你有了一个接口,你就可以使用一些第三方库来自动生成模拟,比如模拟

An example on how to create the interface关于如何创建接口的示例

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

Just change any function that receives a mongodb cursor to use the custom interface只需更改接收 mongodb cursor 的任何 function 以使用自定义接口

I just ran into this problem.我刚刚遇到了这个问题。 Because mongo.Cursor has an internal field that holds the []byte -- Current , in order to fully mock you'll need to wrap the mongo.Cursor .因为mongo.Cursor有一个内部字段保存[]byte - Current ,为了完全模拟你需要包装mongo.Cursor Here are the types I made to do this:以下是我为此所做的类型:

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
}

Unfortunately this will be a bit of a moving target.不幸的是,这将是一个移动的目标。 I'll have to add new functions to the MongoCollection interface as time goes on.随着时间的推移,我将不得不向MongoCollection接口添加新功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM