金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks

# go代码覆盖测试


(金庆的专栏 2020.2)

假设应用名为 MyMod, 主函数的文件为 main.go, 那就创建如下的 main_test.go 文件:
```
package main

/* 测试整个服务器。
    go test -c -covermode=count -coverpkg ./...
生成 MyMod.test.exe. 复制到 bin 目录下运行:
    MyMod.test.exe --systemTest --test.coverprofile MyMod.cov
生成代码覆盖测试结果 MyMod.cov, 需要在 go.mod 管理的目录下执行
    go tool cover -html=MyMod.cov -o MyMod.html
打开 MyMod.html 查看结果。
*/

import (
    "flag"
    "fmt"
    "testing"
)

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 {
        fmt.Println("Test system...")
        main()
    }
}
```

MyMod.cov 会积累,可加入 Git.
MyMod.cov 提交前,需对其排序,方便查看 diff.

排序脚本 sort_cov.bat 如下:
```
head -1 MyMod.cov > tmp.cov
cat MyMod.cov | sed '1d' | sort >> tmp.cov
cp tmp.cov MyMod.cov
del tmp.cov
pause
```

posted on 2020-02-29 09:10 金庆 阅读(353) 评论(0)  编辑 收藏 引用 所属分类: 3. Golang

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理