我有一个用 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 如果第二个元素首先出现,则测试用例仍应通过。我该怎么做?到目前为止,我使用mapsets from 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)) 910 expectedContexts := mapset.NewSet(). // mapset comes from here https://github.com/deckarep/golang-set11 var jsonMap map[string](interface{})12 var b []byte1314 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)1819 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)2324 receivedContexts := mapset.NewSet() // mapset comes from here https://github.com/deckarep/golang-set25 receivedContexts.Add(myList[0])26 receivedContexts.Add(myList[1])2728 assert.Equal(t, expectedContexts, receivedContexts)但是当我运行这个测试用例时,当我尝试将一个项目添加到地图集时,我在第 17 行收到以下错误:panic: runtime error: hash of unhashable type map[string]interface {}如何mapset正确添加这些项目?是否有更好/更容易/不同的方法来进行此验证?
1 回答
BIG阳
TA贡献1859条经验 获得超6个赞
您可以使用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)
比较函数根据匹配结果返回一个布尔值。如果它返回 true,您可以断言它。
- 1 回答
- 0 关注
- 102 浏览
添加回答
举报
0/150
提交
取消