【问题标题】:Golang: reflect.DeepEqual returns unexpected falseGolang:reflect.DeepEqual 返回意外的错误
【发布时间】:2019-09-10 19:36:53
【问题描述】:

我在下面有以下代码和代码测试,由于某种原因,deepEqual 返回 false 并且测试失败。现在通过阅读有关此的文档,我希望这会以真正的方式通过如此简单的事情?任何点将不胜感激。谢谢

// 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 [] []}

【问题讨论】:

    标签: go testing tdd


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-10
      • 2022-11-21
      • 2015-05-09
      • 2015-08-23
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 2012-06-19
      相关资源
      最近更新 更多