golang test传参数实践

背景

有时候我们在写代码是,需要将test编译成单独的可执行文件进行测试,并且在test中传参。

go version
go version go1.15.1 darwin/amd64

demo

package action

import (
    "flag"
    "fmt"
    "testing"
)

var cc = flag.String("cc", "11", "")

func TestInit2(t *testing.T) {
    flag.Parse()
}

func TestWildDomain(t *testing.T) {
    fmt.Println("cc:", *cc)
}

测试

go test  t_test.go -cc=222 -v
=== RUN   TestInit2
--- PASS: TestInit2 (0.00s)
=== RUN   TestWildDomain
cc: 222
--- PASS: TestWildDomain (0.00s)
PASS
ok      command-line-arguments  0.615s

go test  t_test.go -cc=11 -v
=== RUN   TestInit2
--- PASS: TestInit2 (0.00s)
=== RUN   TestWildDomain
cc: 11
--- PASS: TestWildDomain (0.00s)
PASS
ok      command-line-arguments  0.223s
./action.test -cc=1120 -test.v
=== RUN   TestInit2
--- PASS: TestInit2 (0.00s)
=== RUN   TestWildDomain
cc: 1120
--- PASS: TestWildDomain (0.00s)
PASS

你可能感兴趣的:(golang test传参数实践)