【Go】单元测试

基本用法

  • 测试文件名以_test结尾
  • 函数名以Test开始

待测试代码

// split.go
package split

import "strings"

func Split(str string, sep string) []string {
	var ret []string
	index := strings.Index(str, sep)
	for index >= 0 {
		ret = append(ret, str[:index])
		str = str[index+len(sep):]
		index  = strings.Index(str, sep)
	}
	ret = append(ret, str)
	return ret
}

测试代码

// split_test.go
package split

import (
	"reflect"
	"testing"
)

func TestSplit(t *testing.T) {
	got := Split("a:b:c", ":")
	want := []string{"a", "b", "c"}
	if !reflect.DeepEqual(got, want) {
		t.Errorf("expected: %v, got: %v\n", want, got)
	}
}

到所在目录执行

go test -v

测试组

优化多个测试用例的代码

func TestSplitByGroup(t *testing.T) {
	type testCase struct {
		str string
		sep string
		want []string
	}

	testGroup := []testCase {
		{"babcbef", "b", []string{"", "a", "c", "ef"}},
		{ "a:b:c", ":", []string{"a", "b", "c"}},
		{"abcef", "bc", []string{"a", "ef"}},
	}

	for _, tg := range testGroup {
		got := Split(tg.str, tg.sep)
		if !reflect.DeepEqual(got, tg.want) {
			t.Errorf("expected: %v, got: %v\n", tg.want, got)
		}
	}
}

子测试

用于区分测试组中,具体执行了哪个测试用例

func TestSplit3(t *testing.T) {
	type testCase struct {
		str  string
		sep  string
		want []string
	}

	testGroup := map[string]testCase{
		"case1": {str: "babcbef", sep: "b", want: []string{"", "a", "c", "ef"}},
		"case2": {str: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
		"case3": {str: "abcef", sep: "bc", want: []string{"a", "ef1"}},
	}

	for name, tg := range testGroup {
		t.Run(name, func(t *testing.T) {
			got := Split(tg.str, tg.sep)
			if !reflect.DeepEqual(got, tg.want) {
				t.Errorf("expected: %#v, got: %#v\n", tg.want, got)
			}
		})
	}
}

测试结果可以看到是case3结果出错了

image-20221119000527171

如果想跑某一个测试用例

go test -run=Split3/case1
go test -run=Split
// 如果run参数错了,找不到测试用例,会warning
// testing: warning: no tests to run

测试覆盖率

  • 函数覆盖率100%
  • 代码覆盖着60%

简单使用

go test -cover

image-20221119001017029

使用工具

go test -cover -coverprofile=cover.out
go tool cover -html=cover.out

image-20221119001337342

基准测试

  • 函数名以Benchmark开始
  • 必须执行b.N
func BenchmarkSplit(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Split("a:b:c", ":")
	}
}

运行

go test -bench=Split
go test -bench .

image-20221119141057822

看内存信息

go test -bench=Split -benchmem

image-20221119141221966

每次操作使用了三次内存分配

还可以重置时间

b.ResetTimer()

Test Main

当测试文件中有TestMain函数,执行go test就会会调用TestMain,否则会创建一个默认的TestMain;我们自定义TestMain时,需要手动调用m.Run()否则测试函数不会执行

func TestMain(m *testing.M) {
	fmt.Println("before code...")
	retCode := m.Run()
	fmt.Println("retCode", retCode)
	fmt.Println("after code...")
	os.Exit(retCode)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值