Golang : reflect. DeepEqual 返回意外的 false

标签 go testing tdd

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

相关文章:

xml - 戈朗 : Compare XML structures

scala - 如何声明必须返回其参数之一的函数的签名? (任何语言*)

c# - ASP.net MVC 4 单元测试 Viewbag/ViewModel 测试

c# - 如何更改被 mock 的对象?

ios - 如何编写一个单元测试来检查我的属性是否在 iOS 上的 dealloc 中释放?

zend-framework - 如何对 zend Action Controller 进行单元测试?

go - 由于同一包中的 undefined object ,dlv 调试失败

angularjs - 如何在 Protractor 中 $rootScope.$broadcast 事件

node.js - 如何使用构造函数和依赖项测试无服务器 lambda 函数?

go - golang 自动收报机是如何工作的?