Search code examples
unit-testinggoassert

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


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]"


Solution

  • 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