使用mongo-go-driver模拟Aggregate遇command failed错误求解决
模拟MongoDB Aggregate函数时返回"command failed"错误的解决求助
我尝试模拟MongoDB的Aggregate函数,但它持续返回通用错误command failed。
待测试函数
func (b *BlogsRepo) CountTagsInBlogs(ctx context.Context) (map[string]int, error) { clog := log.GetLoggerFromContext(ctx) // 指定分组统计标签的管道 pipeline := []bson.M{ { "$unwind": "$tags", }, { "$group": bson.M{ "_id": "$tags", "count": bson.M{"$sum": 1}, }, }, } // 根据管道聚合数据 cursor, err := b.collection.Aggregate(ctx, pipeline) if err != nil { clog.ErrorCtx(err, log.Ctx{ "msg": "Error aggregating data", "err": err, }) return nil, err } defer cursor.Close(ctx) // 创建存储标签计数的map tagCounts := make(map[string]int) // 遍历结果并填充map for cursor.Next(ctx) { var result struct { Tag string `bson:"_id"` Count int `bson:"count"` } if err := cursor.Decode(&result); err != nil { clog.ErrorCtx(err, log.Ctx{ "msg": "Error decoding result"}, ) return nil, err } tagCounts[result.Tag] = result.Count } return tagCounts, nil }
测试代码
func TestBlogsRepo_CountTagsInBlogs(t *testing.T) { mt := mtest.New(t, mtest.NewOptions().ClientType(mtest.Mock)) defer mt.Close() ctx := context.TODO() testCases := []struct { name string mockedResponse []bson.D expected map[string]int err error }{ { name: "successful count tags response", mockedResponse: []bson.D{ {{"_id", "java"}, {"count", 3}}, {{"_id", "go"}, {"count", 7}}, {{"_id", "kotlin"}, {"count", 3}}, }, expected: map[string]int{ "java": 3, "go": 7, "kotlin": 3, }, err: nil, }, } for _, tc := range testCases { tc := tc mt.Run(tc.name, func(mt *mtest.T) { // 模拟聚合响应 mt.AddMockResponses(tc.mockedResponse...) blogRepo := NewBlogRepository(mt.Client, mt.Coll) // 调用待测试方法 tagCounts, err := blogRepo.CountTagsInBlogs(ctx) // 校验返回值与预期是否一致 assert.Equal(t, tc.expected, tagCounts, "Tag counts do not match expected values") assert.NoError(t, err) }) } }
报错信息
Error: Received unexpected error: command failed Test: TestBlogsRepo_CountTagsInBlogs
错误发生在以下代码段:
cursor, err := b.collection.Aggregate(ctx, pipeline) if err != nil { clog.ErrorCtx(err, log.Ctx{ "msg": "Error aggregating data", "err": err, }) return nil, err } defer cursor.Close(ctx)
捕获该错误后会返回nil map,进而导致与预期结果不匹配。我认为自己的Mock配置没有问题,希望能得到解决建议。
内容的提问来源于stack exchange,提问作者Mike3355
相关产品推荐
相关产品推荐

