我有一个函数,它应该根据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.4
和go1.9