我有一個用 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 關注
- 118 瀏覽
添加回答
舉報
0/150
提交
取消