单元测试

golang系统包就继承了单元测试
这里演示表格驱动的方式,进行单元测试
示例:
待测试函数

package test

func Add(a, b int) int {
	return a + b
}
add_test.go
package test

import (
	"fmt"
	"os"
	"testing"
)

func TestAdd(t *testing.T) {
	type args struct {
		a int
		b int
	}
	tests := []struct {
		name string
		args args
		want int
	}{
		{"t1",args{1,2},3},
		{"t2",args{3,5},8},
		{"t3",args{3,5},9},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := Add(tt.args.a, tt.args.b); got != tt.want {
				t.Errorf("Add() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestMain(m *testing.M) {
	fmt.Println("begin")
	// os.Exit()参数为状态码,如果 !=0,则立刻终止程序
	os.Exit(m.Run())
	fmt.Println("end")
}
go test -v
begin
=== RUN   TestAdd
=== RUN   TestAdd/t1
=== RUN   TestAdd/t2
=== RUN   TestAdd/t3
    add_test.go:26: Add() = 8, want 9
--- FAIL: TestAdd (0.00s)
    --- PASS: TestAdd/t1 (0.00s)
    --- PASS: TestAdd/t2 (0.00s)
    --- FAIL: TestAdd/t3 (0.00s)
FAIL
exit status 1
FAIL    coolcar/test    0.699s

压力测试

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

运行:

$ go test -bench=.
goos: windows
goarch: amd64
pkg: coolcar/test
BenchmarkAdd-8          1000000000               0.746 ns/op
PASS
ok      coolcar/test    1.090s