Golang测试断言函数返回的nil失败。

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

golang test assert the nil return from function is failing

问题

我正在尝试断言一个返回nil的函数,但是我尝试断言nil时,以下断言就没有意义了。
我正在使用github.com/stretchr/testify/assert框架进行断言。

通过:assert.Equal(t, meta == nil, true)

失败:assert.Equal(t, meta, nil)

我不确定为什么这样做有任何意义。有人可以帮忙吗?

被测试的方法:

type Metadata struct {
	UserId          string
}

func GetAndValidateMetadata(metadata map[string]string) (*Metadata, error) {
	userId := metadata["userId"]
	if userId == "" {
		return nil, errors.New("userId is undefined")
	}
	meta := Metadata{
		UserId:          userId,
	
	}
	return &meta, nil
}

测试用例:

func TestValidation(t *testing.T) {
	metadata := map[string]string{
		"fakeUserId": "testUserId",
	}
	meta, err := GetAndValidateMetadata(metadata)

 assert.Equal(t, meta == nil, true) <--- 通过
 assert.Equal(t, meta, nil) <--- 失败
}
英文:

I am trying to assert a function that returns a nil, but i'm trying to assert nil but the following assertion doesn't make sense.
I am using the github.com/stretchr/testify/assert framework to assert

passes: assert.Equal(t, meta == nil, true)

fails: assert.Equal(t, meta, nil)

I am not sure why this makes any sense. could someone help please.

Method being tested:

type Metadata struct {
	UserId          string
}

func GetAndValidateMetadata(metadata map[string]string) (*Metadata, error) {
	userId _ := metadata[&quot;userId&quot;]
	if userId == &quot;&quot; {
		return nil, errors.New(&quot;userId is undefined&quot;)
	}
	meta := Metadata{
		UserId:          userId,
	
	}
	return &amp;meta, nil
}

testcase:

func TestValidation(t *testing.T) {
	metadata := map[string]string{
		&quot;fakeUserId&quot;: &quot;testUserId&quot;,
	}
	meta, err := GetAndValidateMetadata(metadata)

 assert.Equal(t, meta == nil, true) &lt;--- passes
 assert.Equal(t, meta, nil) &lt;--- fails
}

答案1

得分: 9

在Go语言中,接口值存储了一个类型和该类型的值。

equal方法接受interface{}类型的参数,所以在第二个断言中,你正在比较一个包含类型信息(*Metadata)和空值的接口值,与一个不包含类型信息和空值的接口值。

你可以通过以下方式强制第二个接口值也包含一个类型:

assert.Equal(t, meta, (*Metadata)(nil))

参见FAQ中的"为什么我的空错误值不等于nil?"

英文:

Interface values in Go store a type and a value of that type.

The equal method takes interface{} arguments, so in the second assertion you are comparing an interface value containing type information (*Metadata) and a nil value to an interface without type information and a nil value.

You can force the second interface to also contain a type like so:

assert.Equal(t, meta, (*Metadata)(nil))

See also "Why is my nil error value not equal to nil?" in the FAQ.

huangapple
  • 本文由 发表于 2022年4月17日 19:32:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/71901511.html
匿名

发表评论

匿名网友

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

确定