我正在从 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)
}
}
一种方法是 to json.Unmarshal
into doc
,但这有时会产生不同的结果。例如,如果 MongoDB 中的文档中有一个数组,那么该数组将被解码doc
为bson.A
类型而不是[]interface{}
类型。