Go語言Test功能測試函數詳解


Go語言的 testing 包提供了三種測試方式,分別是單元(功能)測試、性能(壓力)測試和覆蓋率測試。

單元(功能)測試

在同一文件夾下創建兩個Go語言文件,分別命名為 demo.go 和 demt_test.go,如下圖所示:


具體代碼如下所示:

demo.go:

  1. package demo
  2. // 根據長寬獲取面積
  3. func GetArea(weight int, height int) int {
  4. return weight * height
  5. }

demo_test.go:

  1. package demo
  2. import "testing"
  3. func TestGetArea(t *testing.T) {
  4. area := GetArea(40, 50)
  5. if area != 2000 {
  6. t.Error("測試失敗")
  7. }
  8. }

執行測試命令,運行結果如下所示:

PS D:\code> go test -v
=== RUN   TestGetArea
--- PASS: TestGetArea (0.00s)
PASS
ok      _/D_/code       0.435s

性能(壓力)測試

將 demo_test.go 的代碼改造成如下所示的樣子:

  1. package demo
  2. import "testing"
  3. func BenchmarkGetArea(t *testing.B) {
  4. for i := 0; i < t.N; i++ {
  5. GetArea(40, 50)
  6. }
  7. }

執行測試命令,運行結果如下所示:

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 代碼改造成如下所示的樣子:

  1. package demo
  2. import "testing"
  3. func TestGetArea(t *testing.T) {
  4. area := GetArea(40, 50)
  5. if area != 2000 {
  6. t.Error("測試失敗")
  7. }
  8. }
  9. func BenchmarkGetArea(t *testing.B) {
  10. for i := 0; i < t.N; i++ {
  11. GetArea(40, 50)
  12. }
  13. }

執行測試命令,運行結果如下所示:

PS D:\code> go test -cover
PASS
coverage: 100.0% of statements
ok      _/D_/code       0.437s


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM