How to test the equivalence of maps in Golang?

前端 未结 8 1346
情歌与酒
情歌与酒 2021-01-30 00:55

I have a table-driven test case like this one:

func CountWords(s string) map[string]int

func TestCountWords(t *testing.T) {
  var tests = []struct {
    input s         


        
8条回答
  •  长发绾君心
    2021-01-30 01:17

    Use cmp (https://github.com/google/go-cmp) instead:

    if !cmp.Equal(src, expectedSearchSource) {
        t.Errorf("Wrong object received, got=%s", cmp.Diff(expectedSearchSource, src))
    }
    

    It does still fail when the map "order" in your expected output is not what your function returns. However, cmp is still able to point out where the inconsistency is.

    For reference, I have found this tweet:

    https://twitter.com/francesc/status/885630175668346880?lang=en

    "using reflect.DeepEqual in tests is often a bad idea, that's why we open sourced http://github.com/google/go-cmp" - Joe Tsai

提交回复
热议问题