登录
首页 >  Golang >  Go问答

使用 Go 编写模拟 MongoDB 的响应

来源:stackoverflow

时间:2024-03-29 11:21:29 359浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《使用 Go 编写模拟 MongoDB 的响应》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我正在从 mongodb 获取文档并将其传递给函数 transform,例如

var doc map[string]interface{}
err := collection.findone(context.todo(), filter).decode(&doc) 
result := transform(doc)

我想为 transform 编写单元测试,但我不确定如何模拟来自 mongodb 的响应。理想情况下,我想设置这样的东西:

func TestTransform(t *testing.T) {
    byt := []byte(`
    {"hello": "world",
     "message": "apple"}
 `)

    var doc map[string]interface{}

    >>> Some method here to Decode byt into doc like the code above <<<

    out := transform(doc)
    expected := ...
    if diff := deep.Equal(expected, out); diff != nil {
        t.Error(diff)
    }
}

一种方法是将 json.unmarshal 转换为 doc,但这有时会产生不同的结果。例如,如果 mongodb 中的文档中有一个数组,则该数组将被解码为 doc 作为 bson.a 类型,而不是 []interface{} 类型。


解决方案


我团队的一名成员最近发现go的官方mongodb驱动程序中有一个隐藏的宝石:https://pkg.go.dev/go.mongodb.org/[email protected]/mongo/integration/mtest。虽然该包处于实验模式并且不保证向后兼容性,但它可以帮助您执行单元测试,至少使用此版本的驱动程序。

您可以查看这篇很酷的文章,其中有大量有关如何使用它的示例:https://medium.com/@victor.neuret/mocking-the-official-mongo-golang-driver-5aad5b226a78。此外,这里是包含本文代码示例的存储库:https://github.com/victorneuret/mongo-go-driver-mock

因此,根据您的示例和文章中的示例,我认为您可以尝试以下操作(当然,您可能需要对此进行调整和实验):

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

    mt.Run("find & transform", func(mt *mtest.T) {
        myollection = mt.Coll
        expected := myStructure{...}

        mt.AddMockResponses(mtest.CreateCursorResponse(1, "foo.bar", mtest.FirstBatch, bson.D{
            {"_id", expected.ID},
            {"field-1", expected.Field1},
            {"field-2", expected.Field2},
        }))

        response, err := myFindFunction(expected.ID)
        if err != nil {
            t.Error(err)
        }

        out := transform(response)
        if diff := deep.Equal(expected, out); diff != nil {
            t.Error(diff)
        }
    })
}

或者,您可以通过与 docker 容器的集成测试以自动化的方式执行更真实的测试。有一些很好的软件包可以帮助您做到这一点:

我采用了 dockertest 库的这种方法,通过 go test -v -run integration 命令来自动化完整的集成测试环境,该环境可以是 setupteardown 。请参阅此处的完整示例:https://github.com/AnhellO/learn-dockertest/tree/master/mongo

希望这有帮助。

终于介绍完啦!小伙伴们,这篇关于《使用 Go 编写模拟 MongoDB 的响应》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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