测试与性能调优

测试

go语言测试文件命名:name_test.go,编译器就是识别这个测试文件。
go test . 执行当前目录下的测试文件。

func TestSubStr(t *testing.T) {
	//表格驱动测试
	tests := []struct {
		s   string
		ans int
	}{
		//Normal cases
		{"abcabcabc", 3},
		{"pwwkew", 3},

		//Edge cases
		{"", 0},
		{"abcabcabcd", 4},
		{"bbbbbb", 1},
		{"b", 1},

		//Chinese support
		{"这是慕课网", 5},
		{"一二三二一", 3},
	}

	for _, tt := range tests {
		//输出错误信息
		if actual := lengthOfNonRepeatingSubStr(tt.s); actual != tt.ans {
			t.Errorf("got %d for input %s; expected %d", actual, tt.s, tt.ans)
		}
	}
}

代码覆盖率和性能测试

go test -coverprofile=c.out //测试代码覆盖率
go tool cover -html=c.out //查看覆盖的代码

go test -bench . //性能测试

func BenchmarkSubstr(b *testing.B) {
	s, ans := "一二三二一", 3
	//b.N是运行多少次,系统自己设置
	for i := 0; i < b.N; i++{
		actual := lengthOfNonRepeatingSubStr(s)
		if actual != ans {
			b.Errorf("got %d for input %s; expected %d", actual, s, ans)
		}
	}

}

使用pprof进行性能调优

go test -bench . -cpuprofile=cpu.out
go tool pprof cpu.out  //查看cpu.out文件
web //查看性能,方块越大,性能损坏越严重

生成文档

go doc fmt.Println //查看文档
godoc -http :8888 //可以查看自己的代码文档。使用注释写文档
godoc -url "http://localhost:6060/pkg/learnGo/queue/">page.html //保存某一页

还可以在test文件中写实例代码,在文档中也可以看到。

func ExampleQueue_Pop() {
	q := Queue{1}
	q.Push(1)
	q.Push(2)

	fmt.Println(q.Pop())
	fmt.Println(q.Pop())

	// output:
	//1
	//1
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值