Golang单测

2022-03-02  本文已影响0人  HueyYao

表格驱动测试:

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
上一篇 下一篇

猜你喜欢

热点阅读