登录
首页 >  Golang >  Go问答

在 Go Mongo-Driver 和 mtest 中模拟 UpdateResult 结果的 UpdateOne 动作

来源:stackoverflow

时间:2024-02-10 22:18:25 109浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《在 Go Mongo-Driver 和 mtest 中模拟 UpdateResult 结果的 UpdateOne 动作》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我正在尝试使用 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 Mongo-Driver 和 mtest 中模拟 UpdateResult 结果的 UpdateOne 动作》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>