Custom command line flags in Go's unit tests

I think I got it what is wrong with flags in my case. With the following command

go test -test.v ./... -gamedir.custom=c:/resources

the compiler runs one or several tests on a workspace. In my particular case there are several tests, because ./... means find and create test executable for every _test.go file found. The test executable applies all the additional params unless one or some of them is ignored within it. Thus the test executables that do use param pass the test, all others fail. This may be overridden by running go test for each test.go separately, with appropriate set of params respectively.


You'll also get this message if you put your flag declarations inside of a test. Don't do this:

func TestThirdParty(t *testing.T) {
    foo := flag.String("foo", "", "the foobar bang")
    flag.Parse()
}

Instead use the init function:

var foo string
func init() {
    flag.StringVar(&foo, "foo", "", "the foo bar bang")
    flag.Parse()
}

func TestFoo() {
    // use foo as you see fit...
}

The accepted answer, I found wasn't completely clear. In order to pass a parameter to a test (without an error) you must first consume that parameter using the flag. For the above example where gamedir.custom is a passed flag you must have this in your test file

var gamedir *string = flag.String("gamedir.custom", "", "Custom gamedir.")

Or add it to the TestMain