Go 知识点(17)— go 工具链 go test 使用
生活随笔
收集整理的這篇文章主要介紹了
Go 知识点(17)— go 工具链 go test 使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
代碼結(jié)構(gòu)
wohu@wohu-dev:~/gocode/src$ tree demo/
demo/
├── main.go
└── main_test.go0 directories, 2 files
wohu@wohu-dev:~/gocode/src$
main_test.go 內(nèi)容:
package mainimport ("fmt""testing"
)func TestPrint(t *testing.T) {// t.SkipNow() res := Print()if res != 100 {t.Errorf("Return wrong value")}
}func TestPrint2(t *testing.T) {res := Print()if res+1 != 101 {t.Errorf("Return wrong value")}
}func TestSequence(t *testing.T) {t.Run("s1", func(t *testing.T) { fmt.Println("s1") })t.Run("s2", func(t *testing.T) { fmt.Println("s2") })t.Run("s3", func(t *testing.T) { fmt.Println("s3") })
}func TestMain(m *testing.M) {fmt.Println("test main start")// 如果沒有調(diào)用 m.Run(),則除了 TestMain 之外其它的 tests 都不會被執(zhí)行m.Run()}func TestAll(t *testing.T) {t.Run("TestPrint", TestPrint)t.Run("TestPrint2", TestPrint2)
}// 注意:使用 Benchmark 時的命令為 go test -bench=.
// 要測試的函數(shù)的運(yùn)行時間必須在 b.N 運(yùn)行次數(shù)是穩(wěn)定的,不能是隨著 i 次數(shù)的增多而增加
func BenchmarkAll(b *testing.B) {for i := 0; i < b.N; i++ {Print()}
}
main.go 內(nèi)容
package mainfunc Print() int {return 100
}
運(yùn)行結(jié)果:
wohu@wohu-dev:~/gocode/src/demo$ go test -v
test main start
=== RUN TestPrint
--- PASS: TestPrint (0.00s)
=== RUN TestPrint2
--- FAIL: TestPrint2 (0.00s)main_test.go:21: Return wrong value
=== RUN TestSequence
=== RUN TestSequence/s1
s1
=== RUN TestSequence/s2
s2
=== RUN TestSequence/s3
s3
--- PASS: TestSequence (0.00s)--- PASS: TestSequence/s1 (0.00s)--- PASS: TestSequence/s2 (0.00s)--- PASS: TestSequence/s3 (0.00s)
=== RUN TestAll
=== RUN TestAll/TestPrint
=== RUN TestAll/TestPrint2
--- FAIL: TestAll (0.00s)--- PASS: TestAll/TestPrint (0.00s)--- FAIL: TestAll/TestPrint2 (0.00s)main_test.go:21: Return wrong value
FAIL
ok demo 0.006s
wohu@wohu-dev:~/gocode/src/demo$
運(yùn)行結(jié)果:
wohu@wohu-dev:~/gocode/src/demo$ go test -bench=.
test main start
s1
s2
s3
goos: linux
goarch: amd64
pkg: demo
BenchmarkAll-4 1000000000 0.280 ns/op
PASS
ok demo 0.332s
wohu@wohu-dev:~/gocode/src/demo$
注意點(diǎn):
- 每個
test文件必須import一個testing包; test case的入?yún)⒈仨殲?t *testing.T或者b *testing.B;t.SkipNow()跳過當(dāng)前test, 并且直接按照Pass處理繼續(xù)下一個testtest文件下的每一個test case均必須以Test開頭,并且符合TestXXX的形式,否則go test會直接跳過測試不執(zhí)行;Go的test不會保證多個TestXXX順序執(zhí)行,但通常會按照順序執(zhí)行,我們不應(yīng)該依賴這個順序;- 使用
t.Run來執(zhí)行subtests可以做到控制test的輸出以及test的順序; - 使用
TestMain作為初始化test, 并且使用m.Run()來調(diào)用其它tests可以完成一些需要初始化操作的testing比如數(shù)據(jù)庫連接、文件打開、restful服務(wù)登錄等;
總結(jié)
以上是生活随笔為你收集整理的Go 知识点(17)— go 工具链 go test 使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Go 学习笔记(80)— Go 标准库
- 下一篇: 2022-2028年中国新型氟塑料行业市