以下均在win10平台
golang go test 工具可以生成二进制测试文件,二进制文件可以使用一些go test的参数,运行
go help testflags
可以看到以下一段话:
For instance, the command
go test -v -args -x -v
will compile the test binary and then run it as
pkg.test -test.v -x -v
即在原来的flag前面加上前缀test.,如-v变成-test.v,自己写一个简单例子:
package main
import (
"fmt"
"testing"
)
func TestA(t *testing.T) {
fmt.Print("TestA\n")
}
func TestB(t *testing.T) {
fmt.Print("TestB\n")
}
生成test.exe文件:go test -c -o test.exe .\fmt_test.go
根据官方示例运行,会发现不行,会报以下错误:
PS D:\goproject> .\test.exe -test.v
flag provided but not defined: -test
Usage of D:\goproject\test.exe:
-test.bench regexp
run only benchmarks matching regexp
...
在搞了好一会儿之后发现,要这样:
.\test.exe --test.v
PS D:\goproject> .\test.exe --test.v
=== RUN TestA
TestA
--- PASS: TestA (0.00s)
=== RUN TestB
TestB
--- PASS: TestB (0.00s)
PASS
需要两个“-”符号
再试试看其他的,如:
PS D:\goproject> .\test.exe --test.run A
TestA
PASS
自定义flag:
package main
import (
"flag"
"fmt"
"testing"
)
func TestA(t *testing.T) {
var a = flag.Int("int", 0, "测试用")
fmt.Printf("TestA : %d\n", *a)
}
打包成test.exe,运行.\test.exe -help会发现没有该flag信息
将a声明为全局变量后:
package main
import (
"flag"
"fmt"
"testing"
)
var a = flag.Int("int", 0, "测试用")
func TestA(t *testing.T) {
fmt.Printf("TestA : %d\n", *a)
}
然后再运行:
PS D:\goproject> .\test.exe -help
Usage of D:\goproject\test.exe:
-int int
测试用
...
PS D:\goproject> .\test.exe --test.run A -int 10
TestA : 10
PASS
自定义flag需要和package一个层级,这样打包工具才能捕捉到