Unit testing 如何在Go中打印数组项的类型?
当我尝试对一些代码进行单元测试时,我有如下断言:Unit testing 如何在Go中打印数组项的类型?,unit-testing,go,Unit Testing,Go,当我尝试对一些代码进行单元测试时,我有如下断言: 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); } 应为:=[]接口{}{1
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);
}
应为:=[]接口{}{1}
实际值:=[]接口{}{float64(1)}
如果!反映。相等(预期、实际);{
t、 误差f(“预期的%#v等于%#v”,实际的,实际的,预期的,预期的);
}
得到了这个输出:
Expected <[]interface {}> []interface {}{1} to equal <[]interface {}> []interface {}{1}
预期[]接口{}{1}等于[]接口{}{1}
如何将此消息打印得更明确
谢谢
您正在打印切片的类型,而不是元素的类型。切片的类型是
[]接口{}
。这就是为什么你会看到
如果要查看元素的动态类型(其静态类型始终为interface{}
),请打印元素的类型:
fmt.Printf("Expected element type: %T, got: %T", expected[0], actual[0])
这将输出:
Expected element type: int, got: float64
注意:
上面的代码假设您将2个切片与1个元素进行比较。如果不想检查切片长度,并且想处理任意长度的切片,可以使用其他动词。例如,您可以使用%t
动词,该动词需要bool
值,并希望打印true
或false
。请注意,这只是一个实现决策,不能保证,但例如使用%t
将打印所有切片元素;如果元素类型为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>})}]
[%!t(int=1)%!t(float64=2)%!t(string=3)
{%!t(int64=63393490800)%!t(int32=0)%!t(*time.Location=&{[]]0}]
它有点难看,但包含许多有用的信息(例如类型、值)。使用
reflect.TypeOf
并调用Name()
。