使用 go-cmp 正确比较和发现两个具有导出成员的结构之间的差异
properly comparing and finding difference between two structs with exported members using go-cmp
我正在编写一个 Go 应用程序,我想为它创建一个测试,
在那个测试中,我从数据库中查询一些东西,将它插入到一个结构中,并将该结构值与我拥有的相同类型的静态结构进行比较,如果它们匹配,则测试成功,如果不匹配,我想显示差异.所以我正在尝试使用 go-cmp
包。
通常我会收到此错误:
panic: cannot handle unexported field at {main.fooTest}.F1.Int.neg:
"math/big".Int
consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported [recovered]
我得到这个是因为我的结构
中有 pgtype.Numeric
type fooTest struct {
I1 int
I2 *int
S1 string
S2 *string
F1 pgtype.Numeric
F2 *pgtype.Numeric
Ff1 float64
Ff2 *float64
Ia1 []int
Ia2 []*int
Ia3 *[]int
Sa1 []string
Sa2 []*string
Sa3 *[]string
Fa1 pgtype.Float8Array
Fa2 *pgtype.Float8Array
Faf1 []float64
Faf2 []*float64
Faf3 *[]float64
}
so I tried to test with `AllowUnnexported` but the `cmp.Equal` line still fails with that error.
if !cmp.Equal(fooFoo, bar,cmp.AllowUnexported(fooTest{})) {
t.Errorf("failed test: %v",cmp.Diff(fooFoo, bar))
}
有什么解决办法吗?
你试过了吗
cmp.Equal(fooFoo, bar, cmp.AllowUnexported(pgtype.Numeric.Int{}))
AllowUnexported
的文档没有提到它递归地将此应用于结构中的所有值。
我正在编写一个 Go 应用程序,我想为它创建一个测试,
在那个测试中,我从数据库中查询一些东西,将它插入到一个结构中,并将该结构值与我拥有的相同类型的静态结构进行比较,如果它们匹配,则测试成功,如果不匹配,我想显示差异.所以我正在尝试使用 go-cmp
包。
通常我会收到此错误:
panic: cannot handle unexported field at {main.fooTest}.F1.Int.neg:
"math/big".Int
consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported [recovered]
我得到这个是因为我的结构
中有pgtype.Numeric
type fooTest struct {
I1 int
I2 *int
S1 string
S2 *string
F1 pgtype.Numeric
F2 *pgtype.Numeric
Ff1 float64
Ff2 *float64
Ia1 []int
Ia2 []*int
Ia3 *[]int
Sa1 []string
Sa2 []*string
Sa3 *[]string
Fa1 pgtype.Float8Array
Fa2 *pgtype.Float8Array
Faf1 []float64
Faf2 []*float64
Faf3 *[]float64
}
so I tried to test with `AllowUnnexported` but the `cmp.Equal` line still fails with that error.
if !cmp.Equal(fooFoo, bar,cmp.AllowUnexported(fooTest{})) {
t.Errorf("failed test: %v",cmp.Diff(fooFoo, bar))
}
有什么解决办法吗?
你试过了吗
cmp.Equal(fooFoo, bar, cmp.AllowUnexported(pgtype.Numeric.Int{}))
AllowUnexported
的文档没有提到它递归地将此应用于结构中的所有值。