Golang: reflect.DeepEqual returns 意外错误
Golang: reflect.DeepEqual returns unexpected false
我有以下代码和下面的代码测试,由于某种原因,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()
returns true
正如预期的那样,这就是你的 t.Errorf()
被调用的原因。
如果它们不相等,您希望测试失败。您只需否定条件:
if !reflect.DeepEqual(got, expected) {
t.Errorf("Got: %v, expected: %v", got, expected)
}
我有以下代码和下面的代码测试,由于某种原因,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()
returns true
正如预期的那样,这就是你的 t.Errorf()
被调用的原因。
如果它们不相等,您希望测试失败。您只需否定条件:
if !reflect.DeepEqual(got, expected) {
t.Errorf("Got: %v, expected: %v", got, expected)
}