Home > Software design >  How to assert map contains key?
How to assert map contains key?

Time:10-06

I have an map object in golang of the type: *map[string]interface{} , how can I assert it contain certain keys? Here is what I have:

type respObj struct {
    ExternalIds *map[string]interface{} `json:"externalIds,omitempty"`
}
myObj := getRespObj()
out, _ := json.Marshal(myObj)
fmt.Println("Response: ", string(out))
// {"externalIds":{"payroll":"bigmoney","serial":"GA3MXX4VV7","vin":"1G1YY3388L5112656"}}
assert.NotNil(t, myObj.ExternalIds)
assert.Contains(t, &myObj.ExternalIds, "payroll")
assert.Contains(t, &myObj.ExternalIds, "serial")
assert.Contains(t, &myObj.ExternalIds, "vin")

Currently throwing error:

Error:          "%!s(**map[string]interface {}=0xc0079bf920)" could not be applied builtin len()

CodePudding user response:

You should pass a map to assert.Contains().

myObj.ExternalIds is a pointer to a map, so &myObj.ExternalIds will be a pointer to a pointer to a map.

Instead of taking its address, dereference the pointer:

assert.Contains(t, *myObj.ExternalIds, "payroll")
assert.Contains(t, *myObj.ExternalIds, "serial")
assert.Contains(t, *myObj.ExternalIds, "vin")

Note that maps are pointers under the hood. Its rare that you need a pointer to a map, passing maps have pointer semantics, and it's efficient (only a pointer is passed under the hood).

  • Related