当我尝试对一些代码进行单元测试时,我有这样的断言:
expected := []interface{}{1}
actual := []interface{}{float64(1)}
if !reflect.DeepEqual(expected, actual); {
t.Errorf("Expected <%T> %#v to equal <%T> %#v", actual, actual, expected, expected);
}
得到这个输出:
Expected <[]interface {}> []interface {}{1} to equal <[]interface {}> []interface {}{1}
如何更明确地打印此消息?
谢谢!
see this code in play.golang.org最佳答案
您打印的是 slice 的类型,而不是元素的类型。 slice 的类型是 []interface{}
.这就是为什么您会看到这一点。
如果您想查看元素的动态类型(它们的静态类型始终为 interface{}
),则打印元素的类型:
fmt.Printf("Expected element type: %T, got: %T", expected[0], actual[0])
输出:
Expected element type: int, got: float64
注意:
以上代码假定您正在比较 2 个 slice 和 1 个元素。如果不想检查 slice 长度,想处理任意长度的 slice ,可以使用其他动词。例如,您可以使用 %t
需要 bool
的动词值并想打印 true
或 false
.请注意,这只是一个实现决定,并不能保证,但使用 %t
例如将打印所有 slice 元素;打印相应的 bool
如果它是 bool
类型的值, 如果不是 bool
类型,将打印元素的动态类型和值.
例子:
data := []interface{}{1, float64(2), "3", time.Now()}
fmt.Printf("%t", data)
输出:
[%!t(int=1) %!t(float64=2) %!t(string=3)
{%!t(int64=63393490800) %!t(int32=0) %!t(*time.Location=&{ [] [] 0 0 <nil>})}]
它有点难看,但包含许多有用的信息(例如类型、值)。
关于unit-testing - 如何在 Go 中打印数组项的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32653109/