golang 統計系統測試覆蓋率


golang 統計系統測試覆蓋率

參考資料

操作步驟

編寫main_test文件

  • 看一下main()函數所在的go文件名稱,直接命名為*test.go文件即可。如motan的main()函數在agent.go中,將main test文件命名為agenttest.go
  • maintest.go與main.go同級目錄,如agent.go與agenttest.go同級目錄
  • main test文件內容如下

package main
// This file is mandatory as otherwise the filebeat.test binary is not generated correctly.
import (
"testing"
"flag"
)
var systemTest *bool
func init() {
systemTest = flag.Bool("systemTest", false, "Set to true when running system tests")
}
// Test started when the test binary is started. Only calls main.
func TestSystem(t *testing.T) {
if *systemTest {
main()
}
}

* main_test.go文件是必須存在的,否則無法生成二進制文件

編譯代碼

  • 將main函數中的os.Exit()更改為return;如果main()函數是啟動server,可以再啟動一個線程啟動server,避免執行到main函數時程序hang住不能執行后面的testcase,如agent.go


func main() {
ext := wmotan.GetWeiboExtentionFactory()
wmotan.UpdateLocalIPByConn("")
agent := motan.NewAgent(ext)
agent.RegisterManageHandler("/200", wmotan.CreateStatusChangeHandler(agent))
agent.RegisterManageHandler("/503", wmotan.CreateStatusChangeHandler(agent))
(&mtool.DebugHandler{}).Register()
//另啟動一個線程啟動服務
go agent.StartMotanAgent()
time.Sleep(time.Second * 60)
return
}

  • 將main.go、maintest.go及main.go中需要的配置文件拷貝到自動化測試工程,如將agent.go及agenttest.go拷貝到測試代碼目錄下,目錄如下:


├── agent.go
├── agent_test.go
├── base
│   ├── base.go
│   └── config.go
├── clientdemo.yaml
├── manage_test.go
├── motan-go-regression.test
├── motan.yaml
├── protocol_test.go
└── server
│ ├── serverdemo.go
│ └── serverdemo.yaml

  • 編譯,參數說明

    • -c表示生成測試二進制文件
    • -covermode=count表示生成的二進制中國年包含覆蓋率計數信息
    • -coverpkg后面要統計覆蓋率的文件源碼
    • -o 后面是輸出的二進制文件名

    go test -c -covermode=count -coverpkg .,../../github.com/weibocom/motan-go/,../../github.com/weibocom/motan-go/cluster,../../github.com/weibocom/motan-go/config,../../github.com/weibocom/motan-go/core,../../github.com/weibocom/motan-go/endpoint,../../github.com/weibocom/motan-go/filter,../../github.com/weibocom/motan-go/ha,../../github.com/weibocom/motan-go/lb,../../github.com/weibocom/motan-go/protocol,../../github.com/weibocom/motan-go/provider,../../github.com/weibocom/motan-go/registry,../../github.com/weibocom/motan-go/serialize,../../github.com/weibocom/motan-go/server -o main.test

  • 執行命令,生成一個二進制文件main.test

  • 啟動服務: -systemTest用於啟動main_test.go中的main函數(啟動server);-test.coverprofile用來指定覆蓋率信息寫入哪個文件

  • 啟動服務后也會自動執行當前目錄下的測試case

./main.test -systemTest -test.coverprofile coverage.cov

  • 執行完畢后(測試用例執行完畢),在當前目錄下會生成coverage.cov文件

統計覆蓋率

  • 使用go工具鏈生成html文件

go tool cover -html=./coverage.cov -o coverage.html

  • 在瀏覽器下打開html文件,格式如下


免責聲明!

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



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