单元测试CountDocument使用MongoDB mongo-driver在Go中

kmpatx3s  于 2023-06-19  发布在  Go
关注(0)|答案(1)|浏览(147)

目前,我正在尝试对用GO编写的mongoDB适配器进行单元测试。我使用mongo-driver的mtest包。
我成功地处理了Update、Find等操作,但很难为CountDocuments创建一个有效的模拟响应。
我尝试了不同的响应,但总是得到invalid response from server, no 'n' field"
我也找不到任何关于这方面的好文件。

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

    mt.Run(mt.Name(), func(mt *mtest.T) {
        itemId := "item-id-to-count"

        mt.AddMockResponses(mtest.CreateCursorResponse(1, "foo.bar", mtest.FirstBatch, bson.D{
            {Key: "n", Value: bson.D{{Key: "Key", Value: "123"}}},
        }))

        memberCount, err := dbCollection.CountDocuments(context.TODO(), bson.M{"_id": itemId}
        if err != nil {
            mt.Error("did not expect an error, got: ", err)
        }
        ...
    })
}

有谁能告诉我mtest.CreateCursorResponse(1,"...)应该是什么样子才能让它工作吗

yhxst69z

yhxst69z1#

您可以执行以下操作来运行mtest for CountDocuments函数的测试:
假设有一个仓库,如下所示:

type mongoRepo struct {
    client *mongo.Client
}

func (r *mongoRepo) Count(ctx context.Context) (int64, error) {
    collection := r.client.Database("test").Collection("restaurants")
    filter := bson.D{}

    return collection.CountDocuments(ctx, filter)
}

然后,您可以使用mtest包执行单元测试,如下所示:

import (
    "context"
    "fmt"
    "testing"

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

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

    mt.Run("count", func(mt *mtest.T) {
        defer func() {
            mt.Client = nil
        }()

        ctx := context.Background()
        mt.AddMockResponses(mtest.CreateSuccessResponse())
        // below code returns the count
        mt.AddMockResponses(mtest.CreateCursorResponse(1, "test.restaurants", mtest.FirstBatch, bson.D{{"n", 1}}))
        
        // For count to work, mongo needs an index. So we need to create that. Index view should contains a key. Value does not matter
        indexView := mt.Coll.Indexes()
        _, err := indexView.CreateOne(ctx, mongo.IndexModel{
            Keys: bson.D{{"x", 1}},
        })
        require.Nil(mt, err, "CreateOne error for index: %v", err)

        repo := &mongoRepo{client: mt.Client}
        count, err := repo.Count(ctx)
        require.Nil(mt, err, "Count error: %v", err)
        require.Equal(mt, int64(1), count, "expected count 1, got %v", count)
    })
}

相关问题