go test flag: flag provided but not defined

倾然丶 夕夏残阳落幕 提交于 2020-12-02 02:45:09

问题


Hi I am using a flag when testing in go:
file_test.go var ip = flag.String("ip", "noip", "test")

I am only using this in one test file. And it works fine when only testing that one test file, but when I run: go test ./... -ip 127.0.0.1 alle of the other test file saying: flag provided but not defined.

Have you seen this?

Regards


回答1:


flag.Parse() is being called before your flag is defined.

You have to make sure that all flag definitions happen before calling flag.Parse(), usually by defining all flags inside init() functions.




回答2:


If you've migrated to golang 13, it changed the order of the test initializer, so it could lead to something like

flag provided but not defined: -test.timeout

as a possible workaround, you can use

var _ = func() bool {
    testing.Init()
    return true
}()

that would call test initialization before the application one. More info can be found on the original thread:

https://github.com/golang/go/issues/31859#issuecomment-489889428



来源:https://stackoverflow.com/questions/29699982/go-test-flag-flag-provided-but-not-defined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!