go test 用args帶參數(shù)
測試中想通過命令行傳遞一些參數(shù)給test func,網(wǎng)上找了一些資料但過程不是很順利,這里記錄一下。
首先go test有一個-args的參數(shù)說可以達到這個目的,但實測下來發(fā)現(xiàn)有沒有沒區(qū)別。。。
google查到的大部分也是用到了flag類型。
flag.go的注釋寫的比較清楚
/*
Package flag implements command-line flag parsing.
Usage:
Define flags using flag.String(), Bool(), Int(), etc.
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
import "flag"
var ip = flag.Int("flagname", 1234, "help message for flagname")
If you like, you can bind the flag to a variable using the Var() functions.
var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}
Or you can create custom flags that satisfy the Value interface (with
pointer receivers) and couple them to flag parsing by
flag.Var(&flagVal, "name", "help message for flagname")
For such flags, the default value is just the initial value of the variable.
After all flags are defined, call
flag.Parse()
to parse the command line into the defined flags.

*/
Package flag implements command-line flag parsing.
Usage:
Define flags using flag.String(), Bool(), Int(), etc.
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
import "flag"
var ip = flag.Int("flagname", 1234, "help message for flagname")
If you like, you can bind the flag to a variable using the Var() functions.
var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}
Or you can create custom flags that satisfy the Value interface (with
pointer receivers) and couple them to flag parsing by
flag.Var(&flagVal, "name", "help message for flagname")
For such flags, the default value is just the initial value of the variable.
After all flags are defined, call
flag.Parse()
to parse the command line into the defined flags.

*/
因此需要做的事情就是:
1. 定義flag,這個需要在main()執(zhí)行之前完成,我這里在test文件里面用全局變量完成,但a可以放在函數(shù)里面。
var (
// Define global args flags.
pA = flag.Int("a", 0, "a.")
a = 0
)
// Define global args flags.
pA = flag.Int("a", 0, "a.")
a = 0
)
2. parse flag,這個要在test func執(zhí)行之前,所以可以考慮加入一個init()在test文件里。
func init() {
flag.Parse()
a = *pA
}
flag.Parse()
a = *pA
}
后面使用這些變量就沒有問題了,比如這樣
func TestInit(t *testing.T) {
flag.Parse()
t.Log("a = ", a)
}
flag.Parse()
t.Log("a = ", a)
}
這里用到的主要是flag的功能,測試用發(fā)現(xiàn)有沒有-args問題不大,所以這個用法可能不是很符合go test的要求,先用起來再說了。
REF
1. https://www.golangtc.com/t/584cbd16b09ecc2e1800000b
2. https://stackoverflow.com/.../process-command-line-arguments-in-go-test
3. https://hsulei.com/2017/08/23/gotest如何使用自定義參數(shù)/