0

My code is simply:

func Test_DecodeLBPolicy(t *testing.T) {
    policy := decodeLBPolicy("lb:RING_HASH")
    require.Equal(t, api.RING_HASH, policy.Type)
    require.Equal(t, nil, decodeLBPolicy(""))
}

problem occurs at last line, the output is as below:

Error:   Not equal: 
         expected: <nil>(<nil>)
         actual  : *api.LBPolicy(nil)

then I tried to replace expected "nil" to "*api.LBPolicy(nil)" it wont compile but when I change the require to require.Equal(t, true, decodeLBPolicy("") == nil) it passed.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
vip15
  • 21
  • 2
  • Answering here because the question is closed (it should not have been, imo). For that particular error it could be resolved with `require.Nil(t, decodeLBPolicy(""))`. – Jeremy Beard May 26 '21 at 16:42

1 Answers1

0

In go, an interface of value nil isn't equal to nil. This is because it has type information associated to it, whereas the nil keyword has no such type. (It also has type nil).

This explains theses lines

    expected: <nil>(<nil>)
    actual  : *api.LBPolicy(nil)

You have a parameter of type *api.LBPolicy and of value nil. But you wanted a type niland value nil.

How to fix is a bit tricky, you could make sure that decodeLBPolicy really return nil and not a interface of value nil. Or compare to a interface of the good type and with the value nil. Or use the == trick as you showed

More details in this post: https://glucn.medium.com/golang-an-interface-holding-a-nil-value-is-not-nil-bb151f472cc7

aureliar
  • 1,476
  • 4
  • 16
  • You are close, but the wording is imprecise, which is required when talking about language specifics. There is no nil type, a nil variable has no type. An interface can be nil, but it contains two values, both of which must be nil. nil is not a keyword, it is a predeclared-identifier used to match zero values. – JimB Feb 08 '21 at 17:56