爲了幫助開發者對代碼進行測試,Go語言也提供了相關的單元測試的基礎框架。除此以外,Go語言還提供了簡單的性能測試框架,給開發者提供了對比和改善算法的便利手段。Go語言的性能測試框架聽說是參考了2002年JavaOne的《How NOT To Write A Microbenchmark》,它的基本測試機理是在必定時間內循環運行測試程序,並最終得出測試程序每次運行的平均時間。不只如此,性能測試框架還支持輸出用於性能調優用的了cpu和內存相關數據。從這方面看,我以爲要比Java、Scala好。程序員
單元測試很重要,Go語言提供了相關的單元測試框架。容許對單個和一系列文件進行自動化測試。算法
Package testing provides support for automated testing of Go packages. It is intended to be used in concert with the 「go test」 command, which automates execution of any function of the formexpress
測試用例寫法bash
函數名稱必須以Test開頭,例如
func TestXxx(*testing.T)
where Xxx can be any alphanumeric string (but the first letter must not be in [a-z]) and serves to identify the test routine. These TestXxx routines should be declared within the package they are testing.app
go文件命名框架
必須是_test.go爲後綴(*_test.go)。此外,package名最好不要用main.ide
舉例, funcs_test.go函數
package mytestoop
import "testing"性能
func TestSomething(t *testing.T) {
//call some function
}
func TestAnotherthing(t *testing.T) {
//call some function
}
go test
將對當前目錄下的全部*_test.go文件進行編譯並自動運行測試。
使用」-file」參數。go test –file **.go 。例如,
go test -file b_test.go
」-file」參數不是必須的,能夠省略。若是你輸入go test b_test.go也會獲得同樣的效果
warning: GOPATH set to GOROOT (c:\go) has no effect
PASS
ok _/F_/workspace/goSample01/src/test 0.359s
go test -run=’ TestSomething’
性能測試對於對比和改進算法頗有幫助。所以,Go語言提供了相關的函數性能測試框架。固然,Go只是提供了基本測試框架,真正的測試代碼還得由程序員來完成。
Benchmark測試用例寫法:
函數命名必須以Benchmark打頭。例如,
func BenchmarkXxx(*testing.B)
are considered benchmarks, and are executed by the "go test" command when the -test.bench flag is provided.
A sample benchmark function looks like this:
func BenchmarkHello(b *testing.B) {
for i := 0; i < b.N; i++ {
fmt.Sprintf("hello")
}
}
在命令行裏輸入:go test . -bench="."
(注意:同一個包裏面不能有相同的方法名。不然,可能會編譯出錯)
F:\workspace\goSample01\src\test>go test . -bench="."
warning: GOPATH set to GOROOT (c:\go) has no effect
PASS
BenchmarkUpdate 500000 4906 ns/op
BenchmarkManual 200000 8750 ns/op
BenchmarkUnroll 500000 4531 ns/op
BenchmarkLoop 2000000000 0.00 ns/op
BenchmarkIteratively 1000000 2078 ns/op
在命令行裏輸入:go test b_test.go -bench="."
F:\workspace\goSample01\src\test>go test b_test.go -bench="."
warning: GOPATH set to GOROOT (c:\go) has no effect
PASS
BenchmarkUpdate 500000 4562 ns/op
BenchmarkManual 200000 9062 ns/op
BenchmarkUnroll 500000 4187 ns/op
ok command-line-arguments 6.953s
1、循環次數和每次操做的時間
The benchmark package will vary b.N until the benchmark function lasts long enough to be timed reliably. The output
testing.BenchmarkHello 10000000 282 ns/op
means that the loop ran 10000000 times at a speed of 282 ns per loop.
2、計時器能夠手工控制
If a benchmark needs some expensive setup before running, the timer may be stopped:
func BenchmarkBigLen(b *testing.B) {
b.StopTimer()
big := NewBig()
b.StartTimer()
for i := 0; i < b.N; i++ {
big.Len()
}
}
GooglePerformanceTools------ Google's pprof
C++ profiler.
http://code.google.com/p/gperftools/wiki/GooglePerformanceTools?redir=1
Usage:
go test [-c] [-i] [build flags] [packages] [flags for test binary]
'Go test' automates testing the packages named by the import paths. It prints a summary of the test results in the format:
ok archive/tar 0.011s
FAIL archive/zip 0.022s
ok compress/gzip 0.033s
...
followed by detailed output for each failed package.
'Go test' recompiles each package along with any files with names matching the file pattern "*_test.go". These additional files can contain test functions, benchmark functions, and example functions. See 'go help testfunc' for more.
By default, go test needs no arguments. It compiles and tests the package with source in the current directory, including tests, and runs the tests.
The package is built in a temporary directory so it does not interfere with the non-test installation.
In addition to the build flags, the flags handled by 'go test' itself are:
-c Compile the test binary to pkg.test but do not run it.
-i
Install packages that are dependencies of the test.
Do not run the test.
The test binary also accepts flags that control execution of the test; these flags are also accessible by 'go test'. See 'go help testflag' for details.
For more about build flags, see 'go help build'. For more about specifying packages, see 'go help packages'.
See also: go build, go vet.
The 'go test' command takes both flags that apply to 'go test' itself
and flags that apply to the resulting test binary.
The test binary, called pkg.test, where pkg is the name of the
directory containing the package sources, has its own flags:
-test.v
Verbose output: log all tests as they are run.
-test.run pattern
Run only those tests and examples matching the regular
expression.
-test.bench pattern
Run benchmarks matching the regular expression.
By default, no benchmarks run.
-test.cpuprofile cpu.out
Write a CPU profile to the specified file before exiting.
-test.memprofile mem.out
Write a memory profile to the specified file when all tests
are complete.
-test.memprofilerate n
Enable more precise (and expensive) memory profiles by setting
runtime.MemProfileRate. See 'godoc runtime MemProfileRate'.
To profile all memory allocations, use -test.memprofilerate=1
and set the environment variable GOGC=off to disable the
garbage collector, provided the test can run in the available
memory without garbage collection.
-test.parallel n
Allow parallel execution of test functions that call t.Parallel.
The value of this flag is the maximum number of tests to run
simultaneously; by default, it is set to the value of GOMAXPROCS.
-test.short
Tell long-running tests to shorten their run time.
It is off by default but set during all.bash so that installing
the Go tree can run a sanity check but not spend time running
exhaustive tests.
-test.timeout t
If a test runs longer than t, panic.
-test.benchtime n
Run enough iterations of each benchmark to take n seconds.
The default is 1 second.
-test.cpu 1,2,4
Specify a list of GOMAXPROCS values for which the tests or
benchmarks should be executed. The default is the current value
of GOMAXPROCS.
For convenience, each of these -test.X flags of the test binary is
also available as the flag -X in 'go test' itself. Flags not listed
here are passed through unaltered. For instance, the command
go test -x -v -cpuprofile=prof.out -dir=testdata -update
will compile the test binary and then run it as
pkg.test -test.v -test.cpuprofile=prof.out -dir=testdata -update
The 'go test' command expects to find test, benchmark, and example functions
in the "*_test.go" files corresponding to the package under test.
A test function is one named TestXXX (where XXX is any alphanumeric string
not starting with a lower case letter) and should have the signature,
func TestXXX(t *testing.T) { ... }
A benchmark function is one named BenchmarkXXX and should have the signature,
func BenchmarkXXX(b *testing.B) { ... }
An example function is similar to a test function but, instead of using *testing
.T
to report success or failure, prints output to os.Stdout and os.Stderr.
That output is compared against the function's "Output:" comment, which
must be the last comment in the function body (see example below). An
example with no such comment, or with no text after "Output:" is compiled
but not executed.
Godoc displays the body of ExampleXXX to demonstrate the use
of the function, constant, or variable XXX. An example of a method M with
receiver type T or *T is named ExampleT_M. There may be multiple examples
for a given function, constant, or variable, distinguished by a trailing _xxx,
where xxx is a suffix not beginning with an upper case letter.
Here is an example of an example:
func ExamplePrintln() {
Println("The output of\nthis example.")
// Output: The output of
// this example.
}
The entire test file is presented as the example when it contains a single
example function, at least one other function, type, variable, or constant
declaration, and no test or benchmark functions.
See the documentation of the testing package for more information.