This question is similar to go test flag: flag provided but not defined, but since that question does not contain a minimal example and the answer is quite high-level, I'm asking it again. In a Go module with a main.go and a main_test.go,
.
├── go.mod
├── go.sum
├── main.go
└── main_test.go
The main.go defines a sayHi flag:
package main
import (
"flag"
"fmt"
)
var sayHi bool
func init() {
flag.BoolVar(&sayHi, "sayHi", false, "Say hi or not")
flag.Parse()
}
func main() {
if sayHi {
fmt.Println("Hi!")
}
}
and the main_test.go is just a placeholder test:
package main
import "testing"
func TestSayHi(t *testing.T) {
}
The problem is that if I try to run the tests, I get a "flag provided but not defined" error:
> go test ./...
flag provided but not defined: -test.testlogfile
Usage of /var/folders/tp/s7nwwdws1wj0z8s0vftppnnc0000gn/T/go-build952058535/b001/my-module.test:
-sayHi
Say hi or not
FAIL github.com/kurtpeek/my-module 0.192s
FAIL
From the answer of the aforementioned question,
You have to make sure that all flag definitions happen before calling
flag.Parse(), usually by defining all flags insideinit()functions.
I don't see how that is not being done here?