在Go中,如何在运行时获得测试环境? [英] In Go,how to get test environment at run time?
本文介绍了在Go中,如何在运行时获得测试环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查代码是否在运行 go test
,以便我可以进行一些配置。
<有没有什么功能可以做到这一点?
赞:
runtime.IsBeingTested()
解决方案
只需指定您在测试的 init
中运行测试。例如,在pkg.go中:
package pkg
var isTesting = false
// ...
在pkg_test.go中:
package pkg
func init(){
isTesting = true
}
// ...
这项技术不仅可以用于 bool
s,但有任何数据或功能。如果你的包中有一些变量(在你的情况下是一个配置变量),你可以在 init
中覆盖它。
I want to check if codes are running for the go test
,so that I could make some configurations.
Is there any function to do that? Like:
runtime.IsBeingTested()
解决方案
Just specify that you run a test in test's init
. For example, in pkg.go:
package pkg
var isTesting = false
// ...
And in pkg_test.go:
package pkg
func init() {
isTesting = true
}
// ...
This technique can be used not just with bool
s but with any data or function. If you have some variable in your package (in your case, a configuration variable), you can just override it in init
.
这篇关于在Go中,如何在运行时获得测试环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文