go的一些測試的方法,懶得跑結果了, 直接上源代碼, 心累!
package main
/**
go 測試相關的一些測試方法
性能測試
超時測試
基準測試
內容正確性測試
代碼覆蓋測試
**/
// 代碼覆蓋測試
// go test -cover -coverprofile=cover.out -covermode=count
// go tool -cover -html=cover.out 以html 頁面打開結果
import (
"os"
"testing"
"time"
)
func TestA(t *testing.T) {}
func TestB(t *testing.T) {}
func Benchmark(t *testing.B) {}
func sum(n ...int) int {
var ret int
ret = 0
for _, i := range n {
ret += i
}
return ret
}
// go test -v -bench .
// go test -v -bench . -benchmem -cpu 1,2,4 -benchtime 30s
func BenchmakSum(b *testing.B) {
for i := 0; i < b.N; i++ {
if sum(1, 2, 3) != 6 {
b.Fatal("sum fatal error")
}
}
}
// benchmark test go test -v -test.bench .
func TestMain(m *testing.M) {
println("Setup")
code := m.Run()
println("teardown")
os.Exit(code)
}
// go test -v -run "(?i)sum"
func TestSum(t *testing.T) {
time.Sleep(time.Second * 2)
if sum(1, 2, 3) != 6 {
t.Fatal("sum error")
}
}
// timeout test go test -v -timeout 3s
func TestTimeout(t *testing.T) {
time.Sleep(time.Second * 5)
}