我有一个函数应该根据 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
,无论我如何尝试,都无法弄清楚出了什么问题。
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)
}
})
}
使用我尝试在
Find
上使用 cursor
来查找所有记录的相同测试用例,它在模拟中工作,在 Find
上模拟它时我得到了所有 3 条记录。
这里可能出现什么问题?
我正在使用
go.mongodb.org/mongo-driver v1.5.4
和 go1.9
我认为您误解了模拟的工作原理 - 您不是说“这是数据,现在就像数据库一样”,您是说“这是如何像数据库一样行事”。当你有
first := mtest.CreateCursorResponse(1, "foo.bar", mtest.FirstBatch, bson.D{
{Key: "_id", Value: "org1"},
{Key: "name", Value: "org1"},
{Key: "api", Value: "key1"},
})
你是说“我们从收藏中得到的第一个东西将是
org1
。”您不是说“有一些数据称为org1
,如果查询匹配则将其发回。”
如果您希望
org2
作为响应,那么您需要告诉它发回 org2
作为第一个响应。