16 软件测试

一、单元测试

依赖 go test命令,在包目录内,所有以 test.go为后缀的源代码文件都是 go test测试的一部分

类型 格式 作用
测试函数 函数名前缀为Test 测试程序的一些逻辑行为是否正确
基准函数 函数名前缀为Benchmark 测试函数的性能
示例函数 函数名前缀为Example 为文档提供示例文档

1.常规测试

package calc

import (
	"testing"
)

func Test1Add(t *testing.T) {
	ret := Add(1, 2) //程序输出结果
	want := 3        //期望结果

	if ret != want {
		t.Errorf("测试用例执行失败![期望值:%v	实际值:%v]\n", want, ret)
	}
}

func Test2Add(t *testing.T) {
	ret := Add(2, 2) //程序输出结果
	want := 4        //期望结果

	if ret != want {
		t.Errorf("测试用例执行失败![期望值:%v	实际值:%v]\n", want, ret)
	}
}

2.测试组

package calc

import (
	"testing"
)

func TestAdd(t *testing.T) {
    
    
	type testCase struct {
    
    
		a   int
		b   int
		ret int
	}

	testGroup := []testCase{
    
    
		testCase{
    
    1, 2, 3},
		testCase{
    
    -1, 2, 1},
		testCase{
    
    0, 2, 2},
	}

	for _, tc := range testGroup {
    
    
		ret := Add(tc.a, tc.b)
		if ret != tc.ret {
    
    
			t.Errorf("测试用例执行失败![期望值:%v	实际值:%v]\n", tc.ret, ret)
		}
	}
}

3.子测试

package calc

import (
	"testing"
)

func TestAdd(t *testing.T) {
    
    
	type testCase struct {
    
    
		a   int
		b   int
		ret int
	}

	testGroup := map[string]testCase{
    
    
		"case_1": testCase{
    
    1, 2, 3},
		"case_2": testCase{
    
    -1, 2, 1},
		"case_3": testCase{
    
    0, 2, 2},
	}

	for name, tc := range testGroup {
    
    
		t.Run(name, func(t *testing.T) {
    
    
			ret := Add(tc.a, tc.b)
			if ret != tc.ret {
    
    
				t.Errorf("测试用例执行失败![期望值:%v	实际值:%v]\n", tc.ret, ret)
			}
		})
	}
}

二、基准测试

在一定负载之下检测程序性能的一种方法

package calc

import (
	"testing"
)

func BenchmarkAdd(b *testing.B) {
    
    
	for i := 0; i < b.N; i++ {
    
    
		Add(1, 2)
	}
}

go test -bench=Add输出结果:

goos: windows
goarch: amd64
pkg: zyz.test.com/calc
cpu: AMD Ryzen 5 5600X 6-Core Processor
BenchmarkAdd-12         1000000000               0.2230 ns/op
PASS
ok      zyz.test.com/calc       0.741s

三、性能调优

func main() {
    
    
	cpufile, err := os.Create("./cpu.pprof")
	if err != nil {
    
    
		fmt.Println(err)
		os.Exit(1)
	}

	pprof.StartCPUProfile(cpufile)
	pprof.WriteHeapProfile(cpufile)

	defer pprof.StopCPUProfile()
	defer cpufile.Close()
}

pprof使用:

# go tool pprof .\cpu.pprof
Type: inuse_space
Time: Mar 21, 2022 at 10:57pm (CST)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top3
Showing nodes accounting for 2787.64kB, 100% of 2787.64kB total
Showing top 3 nodes out of 16
      flat  flat%   sum%        cum   cum%
 1762.94kB 63.24% 63.24%  1762.94kB 63.24%  runtime/pprof.StartCPUProfile
  512.50kB 18.38% 81.63%   512.50kB 18.38%  runtime.allocm
  512.20kB 18.37%   100%   512.20kB 18.37%  runtime.malg
(pprof)

扩展:

1.安装 graphviz工具可以图形化展示

2.go-torch和FlameGraph可以画火焰图

3.wrk压测工具

猜你喜欢

转载自blog.csdn.net/pointerz_zyz/article/details/123649036
16