卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35051本站已运行393

使用 Go Mongo-Driver 和 mtest 从 UpdateOne 模拟 UpdateResult

使用 go mongo-driver 和 mtest 从 updateone 模拟 updateresult

php小编百草在这篇文章中将介绍如何使用Go Mongo-Driver和mtest从UpdateOne模拟UpdateResult。通过这种方法,我们可以在测试环境中模拟出UpdateResult对象,并对其进行各种操作和验证。这种技术可以帮助开发人员更好地测试和调试他们的代码,确保其在生产环境中的稳定性和可靠性。本文将详细介绍使用Go Mongo-Driver和mtest的步骤和示例代码,帮助读者快速上手并应用于实际项目中。让我们一起来探索吧!

问题内容

我正在尝试使用 mtest 包(https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo/integration/mtest)对我的 mongodb 调用执行一些模拟结果测试,但我似乎无法弄清楚如何正确模拟对集合进行 updateone(...) 调用时返回的 *mongo.updateresult 值。

这是演示该问题的代码片段:

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")
    })
}

collection.updateone(context.background(), filter, update) 调用工作得很好。没有返回任何错误。不幸的是,updateresult.modifiedcount 值始终为 0。

我尝试了 mtest.createsuccessresponse(...) 和 和 bson.d 的多种组合,使用 nmodifiedn (如代码片段中所示)等名称,以及 modifiedcount matchedcountphp cnendcphpcn.cn似乎没有什么可以解决问题。

是否有办法模拟此调用,使其实际上返回 modifiedcount 的值?

解决方法

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

这对我获得 modifiedcount 有用:1

卓越飞翔博客
上一篇: go-gorm 查询多位字段
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏