阿里云携手百名商业领袖、技术大咖,带您一探行进中的数字新基建!>>>
golang 统计系统测试覆盖率参考资料
- https://www.elastic.co/blog/code-coverage-for-your-golang-system-tests
- https://www.cnblogs.com/zhaoxd07/p/8028847.html
操作步骤
编写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 *boolfunc 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函数中的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}
├── 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
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 -test.coverprofile coverage.cov
- 执行完毕后(测试用例执行完毕),在当前目录下会生成coverage.cov文件
统计覆盖率
- 使用go工具链生成html文件
go tool cover -html=./coverage.cov -o coverage.html
这里给大家推荐一个在线软件复杂项交易平台:米鼠网 https://www.misuland.com
米鼠网自成立以来一直专注于从事软件项目、人才招聘、软件商城等,始终秉承“专业的服务,易用的产品”的经营理念,以“提供高品质的服务、满足客户的需求、携手共创双赢”为企业目标,为中国境内企业提供国际化、专业化、个性化、的软件项目解决方案,我司拥有一流的项目经理团队,具备过硬的软件项目设计和实施能力,为全国不同行业客户提供优质的产品和服务,得到了客户的广泛赞誉。
