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

huangapple go评论120阅读模式
英文:

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

问题

这是一个示例,文档中展示了这样的示例代码:

assert.Contains(t, {"Hello": "World"}, "Hello", "但是 {'Hello': 'World'} 包含 'Hello'")

但是运行这段代码会失败:

  1. mymap := map[string]string{}
  2. mymap["Hello"] = "World"
  3. 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

  1. mymap := map[string]string{}
  2. mymap["Hello"] = "World"
  3. 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

我检查了一下,对我来说它运行得很好。你确定显示的错误与那段代码有关吗?这是我尝试的代码:

  1. package main
  2. import "testing"
  3. import "github.com/stretchr/testify/assert"
  4. func TestContains(t *testing.T) {
  5. mymap := map[string]string{}
  6. mymap["Hello"] = "World"
  7. assert.Contains(t, mymap, "Hello")
  8. }

而且测试没有失败:

  1. go test stackoverflow/35387510/contains_test.go
  2. 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:

  1. package main
  2. import "testing"
  3. import "github.com/stretchr/testify/assert"
  4. func TestContains(t *testing.T) {
  5. mymap := map[string]string{}
  6. mymap["Hello"] = "World"
  7. assert.Contains(t, mymap, "Hello")
  8. }

And the test doesn't fail:

  1. go test stackoverflow/35387510/contains_test.go
  2. ok command-line-arguments 0.009s

答案2

得分: 0

看起来你正在使用类型断言。以下是翻译好的代码部分:

  1. package main
  2. import "testing"
  3. import "github.com/stretchr/testify/assert"
  4. func TestContains(t *testing.T) {
  5. // 将 assert 初始化如下
  6. assert := assert.New(t)
  7. mymap := map[string]string{}
  8. mymap["Hello"] = "World"
  9. // 在 contains 中不需要传递 t
  10. assert.Contains(mymap, "Hello")
  11. }

你可以在这里的文档中了解有关类型断言中的 contains 的更多信息。

英文:

Looks like you must be using type assertion

  1. package main
  2. import "testing"
  3. import "github.com/stretchr/testify/assert"
  4. func TestContains(t *testing.T) {
  5. // Initialize assert as below
  6. assert := assert.New(t)
  7. mymap := map[string]string{}
  8. mymap["Hello"] = "World"
  9. //then no need to pass t in contains
  10. assert.Contains(mymap, "Hello")
  11. }

In docs which for contains in type assertions

huangapple
  • 本文由 发表于 2016年2月14日 09:47:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/35387510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定