我有一个用 Go 编写的端点。当您使用 GET 请求调用它时,它会在成功时返回以下数据 (200):
{"Q":[{"A":"D","M":{"F":{"J":4,"K":3,"L":1}},"R":"S"},{"A":"E","M":{"F":{"J":4,"K":3,"L":1}},"R":"T"}]}
现在我正在尝试编写一个测试用例,它将检查来自该端点的返回数据并确保它与上面一样。但是列表中两个对象的顺序无关紧要。 IE 如果第二个元素首先出现,则测试用例仍应通过。我该怎么做?
到目前为止,我正在使用
mapset
来自 here在测试用例中实现无序列表,如下所示: 1 statusCode, bodyBytes, err := myHTTPRequestFunc(http.MethodGet, uri, headers, bytes.NewBuffer(body))
2 assert.Nil(t, err)
3 unmarshalledBody := make(map[string]interface{})
4 err = json.Unmarshal(bodyBytes, &unmarshalledBody)
5 assert.Nil(t, err)
6 assert.Equal(t, http.StatusOK, statusCode)
7 myList := unmarshalledBody["Q"].([]interface{})
8 assert.Equal(t, 2, len(myList))
9
10 expectedContexts := mapset.NewSet(). // mapset comes from here https://github.com/deckarep/golang-set
11 var jsonMap map[string](interface{})
12 var b []byte
13
14 jsonMap = make(map[string](interface{}))
15 b = []byte(`{"A":"D","M":{"F":{"J":4,"K":3,"L":1}},"R":"S"}`)
16 assert.Nil(t, json.Unmarshal([]byte(b), &jsonMap))
17 expectedContexts.Add(jsonMap)
18
19 jsonMap = make(map[string](interface{}))
20 b = []byte(`{"A":"E","M":{"F":{"J":4,"K":3,"L":1}},"R":"T"}`)
21 assert.Nil(t, json.Unmarshal([]byte(b), &jsonMap))
22 expectedContexts.Add(jsonMap)
23
24 receivedContexts := mapset.NewSet() // mapset comes from here https://github.com/deckarep/golang-set
25 receivedContexts.Add(myList[0])
26 receivedContexts.Add(myList[1])
27
28 assert.Equal(t, expectedContexts, receivedContexts)
但是当我运行这个测试用例时,当我尝试将一个项目添加到 map 集时,我在第 17 行收到以下错误:panic: runtime error: hash of unhashable type map[string]interface {}
如何将这些项目添加到 mapset
适本地?是否有更好/更容易/不同的方法来进行此验证?
最佳答案
您可以使用 reflect.DeepEqual
将未编码的主体界面与您选择的预期结果进行比较的功能
假设您有 unmarshalledBody
已经可用,根据您的预期结果形成界面以将其与
expected := `{"Q":[{"A":"D","M":{"F":{"J":4,"K":3,"L":1}},"R":"S"},{"A":"E","M":{"F":{"J":4,"K":3,"L":1}},"R":"T"}]}`
expectedBody := make(map[string]interface{})
if err := json.Unmarshal([]byte(expected), &expectedBody); err != nil {
return
}
result := reflect.DeepEqual(unmarshalledBody, expectedBody)
比较函数根据匹配结果返回一个 bool 值。如果它返回 true,您可以断言它。Go playground demo
关于go - 如何将 JSON 对象验证为无序列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64058480/