snu*_*182 8 unit-testing go command-line-arguments
有一个模块化的应用程序.有一堆测试使用一组应用程序模块,每个测试需要不同的设置.一些模块通过命令行进行调整,例如:
func init() {
flag.StringVar(&this.customPath, "gamedir.custom", "", "Custom game resources directory")
}
Run Code Online (Sandbox Code Playgroud)
但我无法测试此功能.如果我跑
go test -test.v ./... -gamedir.custom=c:/resources
Run Code Online (Sandbox Code Playgroud)
运行时回答
flag provided but not defined: -gamedir.custom
Run Code Online (Sandbox Code Playgroud)
并且未通过测试.
我在测试命令行参数时做错了什么?
snu*_*182 15
我想在我的情况下我得到了旗帜有什么问题.使用以下命令
go test -test.v ./... -gamedir.custom=c:/resources
Run Code Online (Sandbox Code Playgroud)
编译器在工作区上运行一个或多个测试.在我的特定情况下,有几个测试,因为./ ...意味着为找到的每个_test.go文件查找并创建测试可执行文件.测试可执行文件应用所有其他参数,除非在其中忽略其中一个或一些.因此,使用param的测试可执行文件通过测试,其他所有测试可执行文件都失败.这可以通过分别使用适当的参数集分别运行每个test.go的go测试来覆盖.
Kev*_*rke 12
如果将标志声明放在测试中,您也会收到此消息.不要这样做:
func TestThirdParty(t *testing.T) {
foo := flag.String("foo", "", "the foobar bang")
flag.Parse()
}
Run Code Online (Sandbox Code Playgroud)
而是使用init函数:
var foo string
func init() {
flag.StringVar(&foo, "foo", "", "the foo bar bang")
flag.Parse()
}
func TestFoo() {
// use foo as you see fit...
}
Run Code Online (Sandbox Code Playgroud)
我发现接受的答案并不完全清楚。为了将参数传递给测试(没有错误),您必须首先使用标志使用该参数。对于上面的示例,其中 gamedir.custom 是通过的标志,您必须在测试文件中包含它
var gamedir *string = flag.String("gamedir.custom", "", "Custom gamedir.")
Run Code Online (Sandbox Code Playgroud)
或者将其添加到TestMain
小智 5
flag.Parse()请注意,从 Go 1.13 开始,如果您使用in ,您将收到以下错误init()
提供但未定义的标志:-test.timeout
要解决此问题,您必须使用 TestMain
func TestMain(m *testing.M) {
flag.Parse()
os.Exit(m.Run())
}
TestFoo(t *testing.T) {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15710 次 |
| 最近记录: |