Search code examples
mongodbgomockingmongo-gomongo-go-driver

Mock UpdateResult From UpdateOne Using Go Mongo-Driver And mtest


I'm trying to use the mtest package (https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo/integration/mtest) to perform some testing with mock results on my MongoDB calls, but I can't seem to figure out how to properly mock the *mongo.UpdateResult value that gets returned when you make an UpdateOne(...) call on a collection.

Here is a snippet demonstrating the problem:

package test

import (
    "context"
    "errors"
    "testing"

    "github.com/stretchr/testify/assert"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/integration/mtest"
)

func UpdateOneCall(mongoClient *mongo.Client) error {
    filter := bson.D{{Key: "SomeIDField", Value: "SomeID"}}
    update := bson.D{{Key: "$set", Value: bson.D{{Key: "ANewField", Value: true}}}}
    collection := mongoClient.Database("SomeDatabase").Collection("SomeCollection")
    updateResult, err := collection.UpdateOne(context.Background(), filter, update)
    if err != nil {
        return err
    }
    if updateResult.ModifiedCount != 1 {
        return errors.New("no field was updated")
    }
    return nil
}

func TestUpdateOneCall(t *testing.T) {
    mt := mtest.New(t, mtest.NewOptions().ClientType(mtest.Mock))
    defer mt.Close()

    mt.Run("Successful Update", func(mt *mtest.T) {

        mt.AddMockResponses(mtest.CreateSuccessResponse(
            bson.E{Key: "NModified", Value: 1},
            bson.E{Key: "N", Value: 1},
        ))

        err := UpdateOneCall(mt.Client)

        assert.Nil(t, err, "Should have successfully triggered update")
    })
}

The collection.UpdateOne(context.Background(), filter, update) call works perfectly fine. There are no errors returned. Unfortunately, the updateResult.ModifiedCount value is always 0.

I've tried multiple combinations of mtest.CreateSuccessResponse(...) and bson.D, utilizing names such as NModified and N (as can be seen in the snippet), as well as ModifiedCount and MatchedCount. Nothing seems to do the trick.

Is there anyway to mock this call such that it actually returns a value for the ModifiedCount?


Solution

  • mt.AddMockResponses(bson.D{
                {"ok", 1},
                {"nModified", 1},
            })
    

    This worked for me to get ModifiedCount : 1