skip to content
Alvin Lucillo

MongoDB mocked response with Go

/ 1 min read

💻 Tech

Unit testing with MongoDB is easier with mtest package from the MongoDB Go driver. For example, you can mock a response for the unit test as shown below:

coll.FindOne(context.TODO(), bson.D{{"name", "user1"}})

Each transaction with the database requires a mocked response. In the test below, CreateCursorResponse is called to simulate the response from FindOne. With this, you can manipulate the data to suit the test case.

Each subtest t instance has its own mongo.Client, which you can inject into your app to work with your collections and documents.

mt.Run("test", func(t *mtest.T) {

    t.AddMockResponses(mtest.CreateCursorResponse(1, "test.users", mtest.FirstBatch, bson.D{{Key: "name": Value: "user1"}}))

    findDocument(t.Client)

})