简体   繁体   中英

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?

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. 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

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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