How to test the equivalence of maps in Golang?

前端 未结 8 1339
情歌与酒
情歌与酒 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

    0 讨论(0)
  • 2021-01-30 01:20

    Simplest way:

        assert.InDeltaMapValues(t, got, want, 0.0, "Word count wrong. Got %v, want %v", got, want)
    

    Example:

    import (
        "github.com/stretchr/testify/assert"
        "testing"
    )
    
    func TestCountWords(t *testing.T) {
        got := CountWords("hola hola que tal")
    
        want := map[string]int{
            "hola": 2,
            "que": 1,
            "tal": 1,
        }
    
        assert.InDeltaMapValues(t, got, want, 0.0, "Word count wrong. Got %v, want %v", got, want)
    }
    
    0 讨论(0)
提交回复
热议问题