Pass Command Line Arguments (Flags) in Go Test


This post show how to pass command line arguments (flags) in Golang test.

The answers found in Google search [1] and Stack Overflow [2] are not working for Go 1.8.1. Finally I found the issues [3] and figure out how to pass arguments correctly. The following is howto.

In Go test code:

package goef

import (
      "flag"
      "testing"
)

var pkgdir = flag.String("pkgdir", "", "dir of package containing embedded files")

func TestGenerateGoPackage(t *testing.T) {
      t.Log(*pkgdir)
}

Note that you do not need to call flag.Parse() in the test code.

You can pass the command line arguments as follows:

$ export PKGDIR=${GOPATH}/src/github.com/siongui/myvfs
$ go test -v embed.go buildpkg.go buildpkg_test.go -args -pkgdir=${PKGDIR}

Note that if -args is not in go test command, the pkgdir string variable in the test code will be empty.


Appendix

You can also use environment variable to pass arguments in Go test.

In Go test code:

package goef

import (
      "os"
      "testing"
)

func TestGenerateGoPackage(t *testing.T) {
      t.Log(os.Getenv("PKGDIR"))
}

Pass arguments as follows:

$ export PKGDIR=${GOPATH}/src/github.com/siongui/myvfs
$ go test -v embed.go buildpkg.go buildpkg_test.go

Tested on: Ubuntu Linux 17.04, Go 1.8.1.


References:

[1]
[2]
[3]
[4]
[5]Good resources for testing in Go : golang
[6]TIL: 'testing' package has a '--short' flag : golang
[7]Dependency management in Go : golang
[8]Unit testing for web apps with postgres! Help wanted! : golang
[9]tests in _test package or not? : golang