文章目录
go 测试模块学习
go 测试的模块 testing
简单的功能测试,侧重于功能正确
被测试代码 位于项目 go/src/项目包/test
package goCode
func Add(a, b int) int {
return a + b
}
测试代码 位于项目 go/src/项目包/test
package goCode_test
import (
"testing"
goCode "tsLearn/goCode"
)
func TestAdd(t *testing.T) {
var a, b, c = 1, 2, 3
real := goCode.Add(a, b)
if real != c {
t.Errorf("error Add")
}
}
使用普通功能测试
cd 项目目录
go test 即可
输出
PASS
ok tsLearn/test 0.002s
侧重于性能测试,测试代码运行速度
被测试 性能 代码,侧重于性能测试
// 不提前分配 ,动态分配函数性能
func MakeSliceWithoutAlloc() []int {
var newSlice []int
for i := 0; i < 100000; i++ {
newSlice = append(newSlice, i)
}
return newSlice
}
// 提前分配确定数量的 函数
func MakeSliceWithPreAlloc() []int {
var newSlice []int
newSlice = make([]int, 0, 100000)
for i := 0; i < 100000; i++ {
newSlice = append(newSlice, i)
}
return newSlice
}
测试性能 代码
func BenchmarkMakeSliceWithoutAlloc(b *testing.B) {
for i := 0; i < b.N; i++ {
goCode.MakeSliceWithoutAlloc()
}
}
func BenchmarkMakeSliceWithPreAlloc(b *testing.B) {
for i := 0; i < b.N; i++ {
goCode.MakeSliceWithPreAlloc()
}
}
使用测试方式
go test -bench=.
goos: linux
goarch: amd64
pkg: tsLearn/test
BenchmarkMakeSliceWithoutAlloc-8 1400 734023 ns/op
BenchmarkMakeSliceWithPreAlloc-8 7796 133683 ns/op
PASS
ok tsLearn/test 2.182s