mongodbgomongo-go

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?


Solution

  • 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