golang 测试命令

版权声明:Just for fun https://blog.csdn.net/ets9p21x/article/details/84189337

单元测试结构

xxx.go 代码文件
xxx_test.go 单元测试文件
func TestXxx() 测试函数
func Benchmark() 性能测试

测试规则

xxx.go

func sum(a, b int) int {
	return a + b
}

xxx_test.go

func TestSum(t *testing.T) {
	var sumList = map[int][]int{
		1:  {1, 0},
		3:  {2, 1},
		20: {5, 3},
	}

	for key, val := range sumList {
		s := sum(val[0], val[1])
		if key != s {
			t.Errorf("%d + %d = %d, or not %d", val[0], val[1], s, key)
		}
	}
}

run

=== RUN   TestSum
--- FAIL: TestSum (0.00s)
    hello_test.go:38: 5 + 3 = 8, or not 20
FAIL

单元测试

go test -h
go test [build/test flags] [packages] [build/test flags & test binary flags]

// 经常使用的命令
go test . // 执行当前目录下的所有测试函数
go test -run=TestSum // 只执行TestSum的测试函数 

-json // 输出json格式的结果
-cover // 代码覆盖率

性能测试

// 将测试样例都测试通过后
go test -bench="."
go test -bench="BenchmarkSum"
func BenchmarkSum(b *testing.B) {
	var a1, a2 int = 1, 1
	for i := 0; i < b.N; i++ {
		a1 = rand.Int() * a2
		a2 = rand.Int() * a1
		c := sum(a1, a2)
		if (a1 + a2) != c {
			b.Errorf("%d != %d", a1+a2, c)
		}
	}
}

result:
BenchmarkSum-4          30000000                44.5 ns/op // 执行了30000000	次,每次耗时45.0 ns
PASS
ok      learntest/hello 2.632s

// 详细分析cpu的运行过程
go test -bench="BenchmarkSum" -cpuprofile cpu.out
// 执行后会生成cpu.out的二进制文件,接下来使用命令:
go tool pprof cpu.out
top

可以观察到哪些程序过程过于耗时
程序运行时间占比

猜你喜欢

转载自blog.csdn.net/ets9p21x/article/details/84189337