go test小记

golang使用test来进行单元测试,命令如下

go test [packages]

上面命令中packages可以省略,如果省略则是directory mode模式,不省略则是package list mode模式。

directory mode模式是运行当前目录下 _test.go 后缀的测试文件。

package list mode模式是运行指定目录下 _test.go 后缀的测试文件。

两者区别是directory mode模式会禁用cache,显示测试文件中的输出,测试结束后会打印状态,package名字以及耗时。

package list mode模式会启用cache,仅仅显示测试结果。如要禁用cache缓存,则可以使用一些flag选项来阻止,比如-count=1。如果要显示一些测试函数中的输出,则需要提供一个-v选项。

 

go test会运行 _test.go 后缀测试文件中以 TestXxx开头的函数,Xxx 可以是任何以字母开头的字母数字字符串,但是第一个字母不能是小写字母,如果是小写的,则不会运行。而 Xxx 到底如何命名是无关紧要的,比如要测试 twoSum( )函数,则可以叫 TestFuncOf2Sum(),这里FuncOf2Sum不需要对应twoSum这个名字,FuncOf2Sum只是用于标识test goroutine的(where Xxx does not start with a lowercase letter. The function name serves to identify the test routine.)。

 

go test 如何运行指定测试函数呢?网上很多博客说使用下面的方法就能运行指定测试函数:

go test -v -test.run TestXxx
//或者
go test -v -run TestXxx

其实这种说法是错误的,因为run选项指定的并不是某个测试函数,而是一个正则匹配,对于 TestXxx  这种函数指明,其实匹配的是 TestXxx*,也即 TestXxx、TestXxx1、TestXxxYyy,这种都是匹配的。

The argument to the -run and -bench command-line flags is an unanchored regular expression that matches the test's name. 

go test -run Foo     # Run top-level tests matching "Foo", such as "TestFooBar".

 

要测试某个具体指定的测试函数,应该使用下面的命令:

go test '-run=^TestXxx$'

run中指定的函数是以Test开头,以Xxx结尾,也就是完全匹配TestXxx这个函数。

 

posted @ 2020-07-13 22:50  impluse  阅读(244)  评论(0编辑  收藏  举报