在golang中使用json marshaling测试深度相等性
发布时间:2020-12-16 19:26:43 所属栏目:大数据 来源:网络整理
导读:鉴于这两个测试用例: func TestEqualWhat(t *testing.T) { testMarshalUnmarshal(t,map[string]interface{}{"a":"b"}) testMarshalUnmarshal(t,map[string]interface{}{"a":5})} testMarshalUnmarshal帮助器只是对json进行编组并返回: func testMarshalUnm
鉴于这两个测试用例:
func TestEqualWhat(t *testing.T) { testMarshalUnmarshal(t,map[string]interface{}{"a":"b"}) testMarshalUnmarshal(t,map[string]interface{}{"a":5}) } testMarshalUnmarshal帮助器只是对json进行编组并返回: func testMarshalUnmarshal(t *testing.T,in map[string]interface{}) { //marshal the object to a string jsb,err := json.Marshal(in); if err != nil { log.Printf("Unable to marshal msg") t.FailNow() } //unmarshal to a map res := make(map[string]interface{}) if err := json.Unmarshal(jsb,&res); err != nil { t.FailNow() } if !reflect.DeepEqual(in,res) { log.Printf("nExpected %#vnbut got %#v",in,res) t.FailNow() } } 为什么第一个测试用例通过而第二个测试用例失败?测试的输出是这样的: Expected map[string]interface {}{"a":5} but got map[string]interface {}{"a":5} --- FAIL: TestEqualWhat (0.00 seconds) Here is similar code on the go playground所以你可以轻松搞定它.
我想到了! JSON只有一个数值类型,它是浮点数,因此所有整数都在marshal / unmarshal进程中转换为Float64.因此,在res map中,5是float64而不是int.
Here是一个游乐场,提供我正在谈论的内容和证据. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |