testify/assert.Contains 如何与地图一起使用?

How is testify/assert.Contains used with a map?

docs 举个例子:

assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'")

但是运行这失败了

mymap := map[string]string{}
mymap["Hello"] = "World"
assert.Contains(t, mymap, "Hello")

导致错误:

Error: "map[Hello:World]" could not be applied builtin len()

切换 mymap 和 "hello" 结果:

Error: "Hello" does not contain "map[Hello:World]"

我检查了一下,对我来说效果很好。您确定显示的错误与该代码有关吗?这就是我的尝试:

package main

import "testing"
import "github.com/stretchr/testify/assert"

func TestContains(t *testing.T) {
    mymap := map[string]string{}
    mymap["Hello"] = "World"
    assert.Contains(t, mymap, "Hello")
}

并且测试没有失败:

→ go test Whosebug/35387510/contains_test.go
ok      command-line-arguments  0.009s

看来您必须使用类型断言

package main

import "testing"
import "github.com/stretchr/testify/assert"

func TestContains(t *testing.T) {
     // Initialize assert as below
    assert := assert.New(t)
    mymap := map[string]string{}
    mymap["Hello"] = "World"
    //then no need to pass t in contains
    assert.Contains(mymap, "Hello")
}

In docs 其中包含类型断言