Custom Command Line Flags in Go Unit Tests

Have a modular application. Have a bunch of tests that use a set of application modules; each test requires a different set. Some modules are configured through the command line, for example:

func init() { flag.StringVar(&this.customPath, "gamedir.custom", "", "Custom game resources directory") } 

But I can not check this functionality. If I run

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

execution responses with

 flag provided but not defined: -gamedir.custom 

and does not pass the test.

How am I wrong when testing command line arguments?

+7
source share
3 answers

I think in my case I realized what is wrong with the flags. Following the command

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

the compiler runs one or more tests in the workspace. In my particular case, there are several tests because. / ... means searching and creating a test executable for each .test.go file found. An executable test applies all additional parameters if one or some of them are not ignored inside it . Thus, test executables that use the param parameter pass the test, all others fail. This can be reversed by running the go test for each test.go separately, with an appropriate set of parameters, respectively.

+14
source

You will also receive this message if you place your flag declarations inside the test. Do not do this:

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

Use the init function instead:

 var foo string func init() { flag.StringVar(&foo, "foo", "", "the foo bar bang") flag.Parse() } func TestFoo() { // use foo as you see fit... } 
+11
source

The accepted answer that I found was not entirely clear. To pass a parameter to the test (without error), you must first use this parameter using the flag. For the above example, where gamedir.custom is the flag you passed, it should be in your test file

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

Or add it to TestMain

+3
source

Source: https://habr.com/ru/post/1208524/


All Articles