How do I pass command line arguments to go test in golang?
syntax.go syntax_test.go syntax.go:
package syntax
import (
"fmt"
"flag"
)
var (
arg string
)
func init(){
flag.StringVar(&arg,"arg","","")
if !flag.Parsed(){
flag.Parse()
}
}
func RandInt() {
fmt.Println("a", arg)
}syntax_test.go:
package syntax
import (
"testing"
)
func TestRandInt(t *testing.T) {
RandInt()
}How to pass in arguments in the command line go test –run TestR
Tested go test –run TestR -argv arg asd and go test –run TestR -argv arg=asd is not true
Answer:
package syntax
import (
"flag"
"fmt"
"testing"
)
var arg string
func init() {
flag.StringVar(&arg, "arg", "", "input arg")
}
func TestRandInt(t *testing.T) {
flag.Parse()
fmt.Println("arg:", arg)
}
then you can test:
bash
go test -args -arg=your_arg➜ syntax ✗ go test -args -arg=asd
flag provided but not defined: -test.paniconexit0
Usage of /var/folders/g_/8yjgqqlx3jl8mjmkzw5tpfr00000gn/T/go-build4074102650/b001/syntax.test:
-arg string
exit status 2
FAIL learn/syntax 0.004s
➜ syntax ✗ go version
go version go1.18.4 darwin/arm64
Leave a Reply