zoukankan      html  css  js  c++  java
  • go测试跨包代码覆盖率

    Golang虽然只是一门编程语言,但也为我们提供了不少工具,其中测试工具是最常用的,大概

    前提概要

      以前看书,只说了用什么工具去做覆盖率,和基本的使用,当时看了也没想太多。后面真正做项目了,老大要求比较规范,每行代码都要跑过,就想到了覆盖率测试工具,但用的时候才发现,按书上的步骤来做,只能测试当前包中的代码,其他包的代码覆盖率没有。

    解决方案

      在查阅了一些问答以后,找到了办法,原来Golang也是有提供的。

      就是使用 “-coverpkg”,具体我们用例子讲解

    Demo

      项目结构如下

      

      代码如下

      main.go

    package gotest
    
    import (
    	"gotest/q"
    )
    
    func main() {
    	q.Print()
    }
    

      q.go

    package q
    
    import (
    	"fmt"
    )
    
    var Q []string
    
    func init() {
    	fmt.Println("q init")
    	Q = append(Q, "q init")
    }
    
    func Print() {
    	fmt.Println("q Print")
    }
    

      go_test.go

    package gotest
    
    import (
    	"testing"
    )
    
    func TestMain(t *testing.T) {
    	main()
    }

      我想测试main函数,而main函数调用了q.go的代码,直接用下面的命令只能测到当前包的。

    go test -coverprofile="c.out"
    go tool cover -html="c.out"

      

      当使用 "-coverpkg"时,就能出现我想要的结果了。

    go test -coverprofile="c.out" -coverpkg=".,./q"
    go tool cover -html="c.out"

       我们也可以用 "..." 表示所有引用到的包,这就比较大了,把标准库都会算进来。

    go test -coverprofile="c.out" -coverpkg="..."
    go tool cover -html="c.out"

    注意

      很多书上的教程运行环境都是Linux的,命令的参数值没有引号包裹,如:

    go test -coverprofile=c.out

      这样在Windows下是会报错的,所以最好用引号包裹起来,这样兼容性较好。

  • 相关阅读:
    黑松白鹿
    跨越
    第三年
    Lua windows环境搭建
    Iron man
    水果沙拉
    六周岁
    sqlserver数据库附加报错5120
    [BeiJing2006]狼抓兔子 平面图最小割
    BZOJ2118: 墨墨的等式 思维建图
  • 原文地址:https://www.cnblogs.com/HuangWj/p/14978365.html
Copyright © 2011-2022 走看看