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 withtest
-- 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 somego 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 aninit()
block, this would count as "too early".The behavior of
go test
options is documented ingo help testflag
: