恐慌:测试:在 Go 中的 Init 案例之前调用 Verbose
尝试跑步 https://github.com/adonovan/gopl。 io/blob/master/ch8/cake/cake_test.go
但得到
panic: testing: Verbose called before Init
goroutine 1 [running]:
testing.Verbose(...)
/usr/lib/go-1.17/src/testing/testing.go:453
.../cake_test.init()
它说错误来自 cake_test.init()
,但 cake_test.go
文件不包含 init()
:
$ grep init cake_test.go | wc
0 0 0
到底是什么问题?
Trying to run
https://github.com/adonovan/gopl.io/blob/master/ch8/cake/cake_test.go
but got
panic: testing: Verbose called before Init
goroutine 1 [running]:
testing.Verbose(...)
/usr/lib/go-1.17/src/testing/testing.go:453
.../cake_test.init()
It says the error comes from cake_test.init()
, yet the cake_test.go
file doesn't contain init()
:
$ grep init cake_test.go | wc
0 0 0
What exactly is the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于这种特定情况,添加 Init() 函数就可以解决问题。
For this specific case, adding Init() function did the trick.
发生这种情况是因为测试包本身有一个 init 来处理测试标志,并且您正在调用 Verbose 来创建全局变量
https://cs.opensource.google/go/go/+/refs/tags/go1.18:src/testing/testing.go;l=548
要避免这种情况,您可以:
func() bool
),但我认为这很复杂另外,考虑创建一个具有与 Println 相同签名的方法
Debug
,如果 Verbose 为 true 则调用 fmt.Println 如果您有一个构造函数,您可以创建第二个字段:Logger,它是一个函数的ponter和与 Println 相同的签名,并使用 fmt.Println 进行初始化,在测试中,您可以设置为 t.Log 以获得更好的体验
当然,也许有些建议比其他建议更先进,请随意尝试一下并选择最好的
This happens because the testing package itself has a init to process test flags and you are callind Verbose to create a global variable
https://cs.opensource.google/go/go/+/refs/tags/go1.18:src/testing/testing.go;l=548
To avoid this you can:
func() bool
) but I think this is complexAlso, Consider create a method
Debug
with same signature of Println, to call fmt.Println if Verbose is trueIf you have a constructor, you can create a second field: Logger, with is a ponter to function with same signature as Println and you initialize with fmt.Println and in the tests you can set as t.Log to have a better experience
Of course perhaps some suggestions are more advanced than others, feel free to play a little bit and choose the best ones