英文:
How is testify/assert.Contains used with a map?
问题
这是一个示例,文档中展示了这样的示例代码:
assert.Contains(t, {"Hello": "World"}, "Hello", "但是 {'Hello': 'World'} 包含 'Hello'")
但是运行这段代码会失败:
mymap := map[string]string{}
mymap["Hello"] = "World"
assert.Contains(t, mymap, "Hello")
会导致以下错误:
错误: "map[Hello:World]" 无法应用内置函数 len()
将 mymap 和 "Hello" 交换位置会导致以下错误:
错误: "Hello" 不包含 "map[Hello:World]"
英文:
the docs show this as an example:
assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'")
But running this fails
mymap := map[string]string{}
mymap["Hello"] = "World"
assert.Contains(t, mymap, "Hello")
results in the error:
Error: "map[Hello:World]" could not be applied builtin len()
switching mymap and "hello" results in this:
Error: "Hello" does not contain "map[Hello:World]"
答案1
得分: 8
我检查了一下,对我来说它运行得很好。你确定显示的错误与那段代码有关吗?这是我尝试的代码:
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 stackoverflow/35387510/contains_test.go
ok command-line-arguments 0.009s
英文:
I checked that and it works fine to me. Are you sure that the displayed error is related to that code? That's what I tried:
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")
}
And the test doesn't fail:
→ go test stackoverflow/35387510/contains_test.go
ok command-line-arguments 0.009s
答案2
得分: 0
看起来你正在使用类型断言。以下是翻译好的代码部分:
package main
import "testing"
import "github.com/stretchr/testify/assert"
func TestContains(t *testing.T) {
// 将 assert 初始化如下
assert := assert.New(t)
mymap := map[string]string{}
mymap["Hello"] = "World"
// 在 contains 中不需要传递 t
assert.Contains(mymap, "Hello")
}
你可以在这里的文档中了解有关类型断言中的 contains 的更多信息。
英文:
Looks like you must be using type assertion
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 which for contains in type assertions
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论