gpt4 book ai didi

Golang : reflect. DeepEqual 返回意外的 false

转载 作者:IT王子 更新时间:2023-10-29 01:56:19 26 4
gpt4 key购买 nike

我在下面有以下代码和代码测试,由于某种原因,deepEqual 返回 false 并未能通过测试。现在,通过阅读关于此的 doco,我希望对于如此简单的事情,它能以正确的方式通过?任何一点将不胜感激。谢谢

// customer.go
type Customer struct {
customerID int
domains []string
names []string
}
func NewCustomer(customerID int, domains []string, names []string) *Customer{
return &Customer{
customerID: customerID,
domains: domains,
names:names,
}
}
// customer_test.go
func TestNewCustomer(t *testing.T) {
expected := &Customer{123,
[]string{},
[]string{},
}

got := NewCustomer(123, []string{}, []string{})

if got.customerID != expected.customerID {
t.Errorf("Got: %v, expected: %v", got.customerID, expected.customerID)
}

if reflect.DeepEqual(got, expected) {
t.Errorf("Got: %v, expected: %v", got, expected)
}
}

输出:

Got: &{123 [] []}, expected: &{123 [] []}

最佳答案

reflect.DeepEqual() 按预期返回 true,这就是调用 t.Errorf() 的原因。

如果它们相等,您希望测试失败。您只需否定条件:

if !reflect.DeepEqual(got, expected) {
t.Errorf("Got: %v, expected: %v", got, expected)
}

关于Golang : reflect. DeepEqual 返回意外的 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55780354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com