
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 的多种组合,使用 nmodified 和 n (如代码片段中所示)等名称,以及 modifiedcount 和 matchedcountphp cnendcphpcn.cn似乎没有什么可以解决问题。</p>
<p>是否有办法模拟此调用,使其实际上返回 <code>modifiedcount 的值?
mt.AddMockResponses(bson.D{
{"ok", 1},
{"nModified", 1},
})这对我获得 modifiedcount 有用:1
以上就是使用 Go Mongo-Driver 和 mtest 从 UpdateOne 模拟 UpdateResult的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号