++wythern++

X presents Y for a better Z

go test 用args带参数

测试中想通过命令行传递一些参数给test func,网上找了一些资料但过程不是很顺利,这里记录一下。
首先go test有一个-args的参数说可以达到这个目的,但实测下来发现有没有没区别。。。
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.

*/
因此需要做的事情就是:
1. 定义flag,这个需要在main()执行之前完成,我这里在test文件里面用全局变量完成,但a可以放在函数里面。
var (
    
// Define global args flags.
    pA = flag.Int("a"0,  "a.")
    a 
= 0
)
2. parse flag,这个要在test func执行之前,所以可以考虑加入一个init()在test文件里。
func init() {
    flag.Parse()
    a 
= *pA
}
后面使用这些变量就没有问题了,比如这样
func TestInit(t *testing.T) {
    flag.Parse()
    t.Log(
"a = ", a)
}
这里用到的主要是flag的功能,测试用发现有没有-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如何使用自定义参数/

posted on 2018-08-14 17:04 wythern 阅读(1836) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理