golang test 二进制文件 flag参数 小问题记录

以下均在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一个层级,这样打包工具才能捕捉到

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值