Go語言的 testing 包提供了三種測試方式,分別是單元(功能)測試、性能(壓力)測試和覆蓋率測試。
單元(功能)測試
在同一文件夾下創建兩個Go語言文件,分別命名為 demo.go 和 demt_test.go,如下圖所示:

具體代碼如下所示:
demo.go:
- package demo
- // 根據長寬獲取面積
- func GetArea(weight int, height int) int {
- return weight * height
- }
demo_test.go:
- package demo
- import "testing"
- func TestGetArea(t *testing.T) {
- area := GetArea(40, 50)
- if area != 2000 {
- t.Error("測試失敗")
- }
- }
執行測試命令,運行結果如下所示:
PS D:\code> go test -v
=== RUN TestGetArea
--- PASS: TestGetArea (0.00s)
PASS
ok _/D_/code 0.435s
性能(壓力)測試
將 demo_test.go 的代碼改造成如下所示的樣子:
- package demo
- import "testing"
- func BenchmarkGetArea(t *testing.B) {
- for i := 0; i < t.N; i++ {
- GetArea(40, 50)
- }
- }
執行測試命令,運行結果如下所示:
PS D:\code> go test -bench="."
goos: windows
goarch: amd64
BenchmarkGetArea-4 2000000000 0.35 ns/op
PASS
ok _/D_/code 1.166s
上面信息顯示了程序執行 2000000000 次,共耗時 0.35 納秒。
覆蓋率測試
覆蓋率測試能知道測試程序總共覆蓋了多少業務代碼(也就是 demo_test.go 中測試了多少 demo.go 中的代碼),可以的話最好是覆蓋100%。
將 demo_test.go 代碼改造成如下所示的樣子:
- package demo
- import "testing"
- func TestGetArea(t *testing.T) {
- area := GetArea(40, 50)
- if area != 2000 {
- t.Error("測試失敗")
- }
- }
- func BenchmarkGetArea(t *testing.B) {
- for i := 0; i < t.N; i++ {
- GetArea(40, 50)
- }
- }
執行測試命令,運行結果如下所示:
PS D:\code> go test -cover
PASS
coverage: 100.0% of statements
ok _/D_/code 0.437s