單元測試,咱們平時也叫它單測,平時開發的時候,也需要寫一些 demo 來測試我們的項目中的函數或者某個小功能【推薦:golang教程】
(資料圖)
GO 語言里面的單元測試,是使用標準庫 testing
有如下簡單規則:
導入 test 標準庫單測文件名,后面跟上_test
單測文件中的函數名為 Test開頭,且參數必須是 t *testing.T
寫一個簡單的例子,添加后綴和前綴
.├── cal.go├── cal_test.go├── lll└── sub.go
cal.go
package mainfunc Addprefix(str string) string { return "hello_"+str}func Addsuffix(str string) string { return str+"_good"}
cal_test.go
package mainimport "testing"func TestAddprefix(t *testing.T) { Addprefix("xiaomotong")}func TestAddsuffix(t *testing.T) { Addsuffix("xiaomotong")}
sub.go
package mainfunc MyAdd(a int, b int) int { if a+b > 10{ return 10 } return a+b}func MySub(one int, two int) int{ if one - two < 0{ return 1 } return one - two}
sub_test.go
package mainimport "testing"import "fmt"func TestMyAdd(t *testing.T) { num := MyAdd(4 ,9) fmt.Println(num) num = MyAdd(4 ,2) fmt.Println(num)}
執行單元測試
go test -v
-v-v 是參數會顯示每個用例的測試結果,顯示執行的單測函數,是否通過以及單測的時候
運行結果如下
=== RUN TestAddprefix--- PASS: TestAddprefix (0.00s)=== RUN TestAddsuffix--- PASS: TestAddsuffix (0.00s)=== RUN TestMyAdd106--- PASS: TestMyAdd (0.00s)PASSok my_new_first/golang_study/later_learning/gotest 0.002s
在包目錄下執行 go test ,會執行包里面所有的單元測試文件
咱們可以這樣用:
go test -run TestMyAdd -v
結果如下:
=== RUN TestMyAdd106--- PASS: TestMyAdd (0.00s)PASSok my_new_first/golang_study/later_learning/gotest 0.002s
就是在我們寫的單測函數中,調用 testing 包里的 Run 方法,跑子測試
咱們改造一下上述的 sub_test.go
package mainimport "testing"import "fmt"func TestMyAdd(t *testing.T) { num := MyAdd(4 ,9) fmt.Println(num) num = MyAdd(4 ,2) fmt.Println(num)}func TestMySub(t *testing.T) { t.Run("one", func(t *testing.T) { if MySub(2, 3) != 1 { t.Fatal("cal error") } }) t.Run("two", func(t *testing.T) { if MySub(3, 1) != 2 { t.Fatal(" error ") } })}
單獨調用子測試函數,執行 go test -run TestMySub/one -v
=== RUN TestMySub=== RUN TestMySub/one--- PASS: TestMySub (0.00s) --- PASS: TestMySub/one (0.00s)PASSok my_new_first/golang_study/later_learning/gotest 0.003s
go test -v -covermode=count -coverprofile=cover.out
go tool cover -html=cover.out -o cover.html
在瀏覽器中打開 html 文件,可以查看到如下報告
UNI-APP開發(仿餓了么)開發課程:進入學習
圖中綠色的部分是已覆蓋,紅色的部分是未覆蓋,咱們的例子已經全部覆蓋具體的函數功能
go test 后面的指令,咱們也可以看幫助文檔
很多公司都開始搞效能了,單測,自動化測試,CI/CD 都是要趕緊搞起來的,最好是做成一鍵發布一鍵回滾的。羨慕這些基礎設置都非常完善的地方,哈哈哈~
以上就是一文搞懂GO中的單元測試(unit testing)的詳細內容,更多請關注php中文網其它相關文章!