test.v 的标志解析 golang 测试失败

golang test fails on flags parse for test.v

在我的go程序中,main方法做了:

port := flag.Int("port", 8080, "Port number to start service on")
flag.Parse()

我有一个看起来像这样的虚拟测试:

func TestName(t *testing.T) {
    fmt.Println("Hello there")
}

当我 运行 我的测试(从 goland 或命令行)时,我遇到了以下错误:

/usr/local/go/bin/go tool test2json -t /private/var/folders/7v/p2t5phhn6cn9hqwjnn_p95_80000gn/T/___TestName_in_github_tools....test -test.v -test.paniconexit0 -test.run ^\QTestName\E$
flag provided but not defined: -test.v
Usage of /private/var/folders/7v/p2t5phhn6cn9hqwjnn_p95_80000gn/T/___TestName_in_github_tools.....test:
  -port int
        Port number to start service on (default 8080)

当我删除main中的标志行时,测试正常执行 请问有什么办法解决这个问题吗?

提前致谢

当你 运行 go test 时,go 实际上将你的代码编译成可执行文件,并执行它。
如果您向 go test 添加选项 - 例如:go test -v - 这些选项实际上传递给测试可执行文件,前缀为 test - 所以 -v 变成-test.v.

(这就是为什么有几条评论询问您用于 运行 测试的确切命令行的原因:因为错误是关于 -test.v,所以可能添加了 -v 一些 go test ... 调用)


看起来 flag.Parse() 正在尝试解析一些实际用于您的测试可执行文件而不是您的代码的参数。

这可能是因为它调用得太早,在测试可执行文件有机会更改 os.Args 切片以删除一些特定标志之前。

检查是什么触发了对 flag.Parse() 的调用:如果它是从 init() 块执行的,这将被视为“太早”。


go test 选项的行为记录在 go help testflag 中:

Each of these flags is also recognized with an optional 'test.' prefix, as in -test.v. When invoking the generated test binary (the result of 'go test -c') directly, however, the prefix is mandatory.

The 'go test' command rewrites or removes recognized flags, as appropriate, both before and after the optional package list, before invoking the test binary.

For instance, the command

go test -v -myflag testdata -cpuprofile=prof.out -x

will compile the test binary and then run it as

pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out