golang 统计系统测试覆盖率

发表于:2019-12-04 11:31

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:sunshine_5    来源:博客园

  操作步骤
  编写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文件,格式如下

      本文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号