我有以下代码和代码测试,由于某种原因,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/