goland go test_Go单元测试实践一,快速上手
- Go單元測(cè)試實(shí)踐二,常見問題
- Go單元測(cè)試實(shí)踐三,代碼風(fēng)格
- Go 單元測(cè)試實(shí)踐四,集成到gitlabci
前段時(shí)間我在團(tuán)隊(duì)內(nèi)推廣了單測(cè),為幫助同事快速上手,寫了一些文檔,這是第一篇,
如果你對(duì)單測(cè),Go都有基礎(chǔ),本文可幫你迅速掌握Go單測(cè)。源碼來自github utdemo倉庫。
1. 背景/工具
Go原生給出了單測(cè)的書寫規(guī)范。有兩條,
2. 測(cè)試函數(shù)命名為Test*,參數(shù)為t *testing.T,如下:
// filename: src.go func Add(a, b int) int {return a + b }// filename: src_test.go package demo import "testing"func TestAdd1(t *testing.T) {if Add(2, 3) != 5 {t.Error("result is wrong!")} else {t.Log("result is right")} }我們額外使用了goconvey這個(gè)工具庫,它提供了一些工具方法,有它寫單測(cè)更方便。其介紹,安裝可參考 goconvey README
2. Goconvey提供了一系列assert工具函數(shù),之后會(huì)常用到,可以在這里查詢
3. 更多樣例可參考github utdemo倉庫。需要提下,測(cè)試會(huì)用到一些公用函數(shù),應(yīng)把它們放置在testutils中以便引用,這個(gè)做法在demo中有展示。
2. 怎樣做調(diào)試?
最方便的方法是使用goland調(diào)試:
效果如下圖
如上方法僅能調(diào)試單個(gè)文件,如要執(zhí)行某包內(nèi)的所有測(cè)試,
- 所有包,運(yùn)行命令:go test ./...
- 僅指定包,運(yùn)行命令:go test ${包名}, 如:go test github.com/xialu4820723/utdemo/file
- 僅指定路徑,運(yùn)行命令: go test ${文件路徑}
如:go test ./file
運(yùn)行命令時(shí),當(dāng)前目錄應(yīng)為項(xiàng)目根目錄
3. 怎么查看測(cè)試覆蓋率?
分兩步:
- 所有包:go test -coverprofile cover.out -coverpkg=./... ./...
- 僅指定包:go test -coverprofile cover.out ${包名},
如:go test -coverprofile cover.out github.com/xialu4820723/utdemo/file
以上命令會(huì)生成名為"cover.out"的文件
2. 展示測(cè)試覆蓋報(bào)告:
html形式:go tool cover -html=cover.out
文字形式:go tool cover -func=cover.out
html格式比較直觀,效果如下圖:
綜覽所有包的測(cè)試覆蓋率:
效果分別如下圖所示
總結(jié)
以上是生活随笔為你收集整理的goland go test_Go单元测试实践一,快速上手的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 除零中断是什么意思?_百万并发「零拷贝」
- 下一篇: 用typescript完成倒计时_「干货