簡介
日常開發中, 測試是不能缺少的.
Go 標準庫中有一個叫做 testing 的測試框架, 可以用于單元測試和性能測試.
它是和命令 go test 集成使用的.
測試文件是以后綴 _test.go 命名的, 通常和被測試的文件放在同一個包中.
單元測試
單元測試的格式形如:
func TestAbs(t *testing.T) { got := Abs(-1) if got != 1 { t.Errorf("Abs(-1) = %d; want 1", got) }}
在 util 目錄下創建一個文件 util_test.go, 添加一個單元測試:
package utilimport "testing"http:// 普通的測試func TestGenShortID(t *testing.T) { shortID, err := GenShortID() if shortID == "" || err != nil { t.Error("GenShortID failed") }}
然后, 在根目錄下運行 go test -v ./util/, 測試結果如下:
root@592402321ce7:/workspace# go test -v ./util/=== RUN TestGenShortID--- PASS: TestGenShortID (0.00s)PASSok tzh.com/web/util 0.006s
性能測試
性能測試的結果形如:
func BenchmarkHello(b *testing.B) { for i := 0; i < b.N; i++ { fmt.Sprintf("hello") }}
在 util_test.go 添加性能測試:
// 性能測試func BenchmarkGenShortID(b *testing.B) { for i := 0; i < b.N; i++ { GenShortID() }}
運行結果如下(使用 --run=none 避免運行普通的測試函數, 因為一般不可能有函數名匹配 none):
root@592402321ce7:/workspace# go test -v -bench="BenchmarkGenShortID$" --run=none ./util/goos: linuxgoarch: amd64pkg: tzh.com/web/utilBenchmarkGenShortID-2 507237 2352 ns/opPASSok tzh.com/web/util 1.229s
這說明, 平均每次運行 GenShortID() 需要 2352 納秒.
性能分析
運行測試的時候, 可以指定一些參數, 生成性能文件 profile.
-blockprofile block.out Write a goroutine blocking profile to the specified file when all tests are complete. Writes test binary as -c would.-blockprofilerate n Control the detail provided in goroutine blocking profiles by calling runtime.SetBlockProfileRate with n. See 'go doc runtime.SetBlockProfileRate'. The profiler aims to sample, on average, one blocking event every n nanoseconds the program spends blocked. By default, if -test.blockprofile is set without this flag, all blocking events are recorded, equivalent to -test.blockprofilerate=1.-coverprofile cover.out Write a coverage profile to the file after all tests have passed. Sets -cover.-cpuprofile cpu.out Write a CPU profile to the specified file before exiting. Writes test binary as -c would.-memprofile mem.out Write an allocation profile to the file after all tests have passed. Writes test binary as -c would.-memprofilerate n Enable more precise (and expensive) memory allocation profiles by setting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'. To profile all memory allocations, use -test.memprofilerate=1.-mutexprofile mutex.out Write a mutex contention profile to the specified file when all tests are complete. Writes test binary as -c would.-mutexprofilefraction n Sample 1 in n stack traces of goroutines holding a contended mutex.
新聞熱點
疑難解答