Golang单测

表格驱动测试:

tests := []struct{
    a, b, c int32
}{
    {1, 2, 3},
    {0, 2, 2},
    {1, 3, 4},
    {math.MaxInt32, 1, math.MinInt32},
}
for _, test := range tests {
    if actual := add(test.a, test.b); actual!= test.c{
        //todo
    }
}
.......

写一个简单的测试用例

需要被测试得代码:

package basic

import (
    "fmt"
    "math"
)
func tryTriangle(a, b int) int{
    var c int
    c = int(math.Sqrt(float64(a*a + b*b)))
    return c
}

func triangle(){
    var a, b int = 3, 4
    fmt.Println(tryTriangle(a, b))
}

测试代码:

package basic

import "testing"

func TestTriangle(t *testing.T){
    tests := []struct{a, b, c int} {
        {3, 4, 5},
        {5, 12, 13},
        {8, 15, 17},
    }
    for _, tt := range tests {
        if actual := tryTriangle(tt.a, tt.b); actual != tt.c {
            t.Errorf("tryTriangle(%d, %d);" + "got %d no %d", tt.a, tt.b, actual, tt.c)
        }
    }
}

验证代码覆盖率

image-20220302224959264.png

测算运行速度

image-20220302225806393.png

如何通过命令进行单侧:

image-20220302225114308.png

通过 go tool cover -html=c.out 来查看覆盖率

测试程序耗时位置:

// 生成性能数据文件
go test -bench . -cpuprofile cpu.out
//打开cpu.out文件 查看性能数据
go tool pprof cpu.out
    web
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • testing testing 提供对 Go 包的自动化测试的支持。通过 go test 命令,能够自动执行如下形...
    DevilRoshan阅读 6,891评论 0 0
  • 大家好,我是李二狗!一起坚持!一起学习!每日一课,无论长短,有所学有所得业精于勤技在专,行则将至事必成 优秀的代码...
    李二狗的星球阅读 3,517评论 0 0
  • 对于web开发者而言,单元测试是项目产品可靠性的重要保障。一个工程项目库的质量是否优秀,通过其在测试方面所做的工作...
    白卡比阅读 4,785评论 0 1
  • 不写测试的开发不是好程序员。我个人非常崇尚TDD(Test Driven Development)的,然而可惜的是...
    吴佳浩阅读 5,907评论 0 2
  • 不写测试的开发不是好程序员。我个人非常崇尚TDD(Test Driven Development)的,然而可惜的是...
    羋学僧阅读 981评论 0 0