1、Go Module下进行单元测试
# 测试example/user包下的所有测试函数
# example是mod中的模块名,user是目录名,-v表示显示用例结果
go test -v example/user
# 测试特定包下的特定方法,-run 后面跟的是正则表达式
go test -v example/user -run ^TestXXXX$
2、问题
现象:程序中使用了flag包定义标志位,在进行单元测试时,报错如下:
flag provided but not defined: -test.v
Usage of C:\Users\201998.INTERNET\AppData\Local\Temp\GoLand\___TestProcessSensitiveData_in_github_com_cyj19_chatroom_logic__1_.test.exe:
-config string
配 置文件所在目录
Process finished with the exit code 1
原因:运行的test.go文件执行到了flag.Parse(), 把go test的test当作一个参数处理,而flag没有对这个参数做处理导致解析失败
解决方法(两种):
- 不要显式或隐式把flag.Parse()放在xxx_test.go中,避免运行go test时执行flag.Parse()
- 在flag.Parse()前增加testing.Init(),把标志位注册到go test命令,这样flag就不会再去解析go test的标志位