In my go program, the main method does:
port := flag.Int("port", 8080, "Port number to start service on")
flag.Parse()
I have a dummy test that looks as:
func TestName(t *testing.T) {
fmt.Println("Hello there")
}
when I run my tests (from the goland or the command line) I got the following error stuck:
/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)
When I remove the lines of the flag in the main, the test executes normally Any idea on how to fix this, please?
Thanks in advance
When you run go test
, go actually compiles your code into an executable, and executes it.
If you add options to go test
-- for example : go test -v
-- these options are actually passed to the test executable, prefixed with test
-- so -v
is turned into -test.v
.
(this is a reason why several comments ask for the exact command line you use to run your tests : since the error is about -test.v
, there probably is something that adds -v
to some go test ...
invocation)
It looks like flag.Parse()
is trying to parse some arguments which are actually intended for your test executable, not for your code.
This is probably because it is called too early, before the test executable has had a chance to alter the os.Args
slice to remove some specific flags.
Check what triggers a call to flag.Parse()
: if it is executed from an init()
block, this would count as "too early".
The behavior of go test
options is documented in 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