7

Pass Command Line Arguments (Flags) in Go Test

 2 years ago
source link: http://siongui.github.io/2017/04/28/command-line-argument-in-golang-test/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Pass Command Line Arguments (Flags) in Go Test

April 28, 2017

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:

[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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK