How to test the equivalence of maps in Golang?

前端 未结 8 1541
情歌与酒
情歌与酒 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 the "Diff" method of github.com/google/go-cmp/cmp:

    Code:

    // Let got be the hypothetical value obtained from some logic under test
    // and want be the expected golden data.
    got, want := MakeGatewayInfo()
    
    if diff := cmp.Diff(want, got); diff != "" {
        t.Errorf("MakeGatewayInfo() mismatch (-want +got):\n%s", diff)
    }
    

    Output:

    MakeGatewayInfo() mismatch (-want +got):
      cmp_test.Gateway{
        SSID:      "CoffeeShopWiFi",
    -   IPAddress: s"192.168.0.2",
    +   IPAddress: s"192.168.0.1",
        NetMask:   net.IPMask{0xff, 0xff, 0x00, 0x00},
        Clients: []cmp_test.Client{
            ... // 2 identical elements
            {Hostname: "macchiato", IPAddress: s"192.168.0.153", LastSeen: s"2009-11-10 23:39:43 +0000 UTC"},
            {Hostname: "espresso", IPAddress: s"192.168.0.121"},
            {
                Hostname:  "latte",
    -           IPAddress: s"192.168.0.221",
    +           IPAddress: s"192.168.0.219",
                LastSeen:  s"2009-11-10 23:00:23 +0000 UTC",
            },
    +       {
    +           Hostname:  "americano",
    +           IPAddress: s"192.168.0.188",
    +           LastSeen:  s"2009-11-10 23:03:05 +0000 UTC",
    +       },
        },
      }
    

提交回复
热议问题