我有一个函数,它应该根据MongoDB a org的过滤器返回,实际上它工作得很好.

func (m *MongoSysService) GetOrg(org string) (types.Org, error) {
    var data types.Org
    if err := m.org.FindOne(context.Background(), bson.D{{Key: "_id", Value: org}}).Decode(&data); err != nil {
        return types.Org{}, err
    }
    return data, nil
}

但后来我试着用mtest来模拟它,结果总是返回第一个结果org1,无论我怎么try ,都找不出问题所在.

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

    mt.Run("success", func(mt *mtest.T) {
        mongoDB.org = mt.Coll

        first := mtest.CreateCursorResponse(1, "foo.bar", mtest.FirstBatch, bson.D{
            {Key: "_id", Value: "org1"},
            {Key: "name", Value: "org1"},
            {Key: "api", Value: "key1"},
        })

        second := mtest.CreateCursorResponse(2, "foo.bar", mtest.NextBatch, bson.D{
            {Key: "_id", Value: "org2"},
            {Key: "name", Value: "org2"},
            {Key: "api", Value: "key2"},
        })

        third := mtest.CreateCursorResponse(3, "foo.bar", mtest.NextBatch, bson.D{
            {Key: "_id", Value: "org3"},
            {Key: "name", Value: "org3"},
            {Key: "api", Value: "key3"},
        })

        killCursors := mtest.CreateCursorResponse(0, "foo.bar", mtest.NextBatch)

        mt.AddMockResponses(first, second, third, killCursors)

        result, err := mongoDB.GetOrg("org2")
        if err != nil {
            t.Fatal(err)
        }
        if result.Name != "org2" || result.GoogleAPIKey != "key2" {
            t.Errorf("Expected %s and %s, got %s and %s", "org2", "key2", result.Name, result.GoogleAPIKey)
        }
    })
}

使用相同的测试用例,我试图在cursor上使用Find来查找所有记录,它在模拟中起作用,当模拟它在Find上时,我得到所有3个记录.

这里的问题可能是什么?

我用的是go.mongodb.org/mongo-driver v1.5.4go1.9

推荐答案

我认为你误解了mock是如何工作的--你不是在说"这是数据,现在像数据库一样工作",你是在说"这是如何像数据库一样工作". 当你有

first := mtest.CreateCursorResponse(1, "foo.bar", mtest.FirstBatch, bson.D{
    {Key: "_id", Value: "org1"},
    {Key: "name", Value: "org1"},
    {Key: "api", Value: "key1"},
})

你说的是"我们从藏品中拿回的第一件东西将是org1美元."您是not,表示"有一些数据称为org1,如果查询匹配,则将其发送回来."

如果你想要org2作为响应,那么你需要告诉它返回org2作为第一个响应.

Mongodb相关问答推荐

$mod只支持数字类型,不支持MongoDb中的array和int

如何在Golang保存到MongoDB时排除空数据值的问题?

MongoDB与合并对象聚合

所有文档中嵌套 struct 中的条件匹配-mongodb

Mongo $sort然后$group,顺序能保证吗?

如何在 MongoDB 中对字段进行自定义排序

DB.collection('comments').find() 不工作

Mongodb聚合查找异常值

Mongoose 返回包含属性内任何位置的值的所有文档

类型错误:db.close is not a function

声明多个模式后无法从数据库中获取数据(mongoose + express + mongodb

将 MongoDB 地理空间索引与 3d 数据结合使用

将 JSON 与 MongoDB 一起使用?

MongoError: The dollar ($) prefixed field '$push' in '$push' is not valid for storage

如何使用 MongoDB C# 驱动程序有条件地组合过滤器?

Java + MongoDB:更新文档中的多个字段

Mongoose - 获取 _id 列表而不是具有 _id 的对象数组

mongoose:按字母顺序排序

使用 $in 进行不区分大小写的搜索

我如何将 mongodb 与electron一起使用?