Page tree
Skip to end of metadata
Go to start of metadata

go test是一个用来运行unit test代码的命令。

这里有一篇文章介绍go test coverage,讲得挺不错的。

使用go test过程中,可以通过 -v 参数来输出测试过程中的相关信息:

go test -v


go test -v -run “Ip2Int”

go tool cover是golang 1.2才推出的一个测试工具,用来检测unittest覆盖测试代码的百分比.我们可以使用下面的命令保存检测的结果:

go test -coverprofile=coverage.out
go tool cover -html=coverage.out


默认情况下,go test 只会执行当前目录(当前目录的包)的测试用例,如果需要包含子目录的测试用例,可以使用 -cover 参数:

go test -v -cover ./...

另外,有时候我们的测试用例和代码并不是在同一个包中,这时候我们可以指定 -coverpkg 参数:

go test -v -coverpkg ./...

对于 -cover ./... 的含义,我们可以看 go help test 的说明:

Go test runs in two different modes:

The first, called local directory mode, occurs when go test is
invoked with no package arguments (for example, 'go test' or 'go
test -v'). In this mode, go test compiles the package sources and
tests found in the current directory and then runs the resulting
test binary. In this mode, caching (discussed below) is disabled.
After the package test finishes, go test prints a summary line
showing the test status ('ok' or 'FAIL'), package name, and elapsed

The second, called package list mode, occurs when go test is invoked
with explicit package arguments (for example 'go test math', 'go
test ./...', and even 'go test .'). In this mode, go test compiles
and tests each of the packages listed on the command line. If a
package test passes, go test prints only the final 'ok' summary
line. If a package test fails, go test prints the full test output.
If invoked with the -bench or -v flag, go test prints the full
output even for passing package tests, in order to display the
requested benchmark results or verbose logging.

对于 -coverpkg ./... 的含义,我们可以看 go help package 的说明:

An import path is a pattern if it includes one or more "..." wildcards,
each of which can match any string, including the empty string and
strings containing slashes. Such a pattern expands to all package
directories found in the GOPATH trees with names matching the

To make common patterns more convenient, there are two special cases.
First, /... at the end of the pattern can match an empty string,
so that net/... matches both net and packages in its subdirectories, like net/http.
Second, any slash-separated pattern element containing a wildcard never
participates in a match of the "vendor" element in the path of a vendored
package, so that ./... does not match packages in subdirectories of
./vendor or ./mycode/vendor, but ./vendor/... and ./mycode/vendor/... do.
Note, however, that a directory named vendor that itself contains code
is not a vendored package: cmd/vendor would be a command named vendor,
and the pattern cmd/... matches it.

  • No labels
Write a comment...