测试用例名称一般命名为 Test 加上待测试的方法名。比如TestAdd(),测试用的参数有且只有一个,在这里是 t *testing.T
简单入门
我们来写一个Add函数,创建文件add.go
package main
import "fmt"
func main() { sum := Add(1, 2) fmt.Println(sum) }
func Add(a int, b int) int { return a + b }
我们在add.go目录下创建一个add_test.go的测试文件
package main
import ( "testing" )
func TestAdd(t *testing.T) { testData := []struct { a int b int c int }{ {1, 2, 3}, {4, 5, 9}, {50, 5, 5}, } ans := 0 for _, data := range testData { if ans = Add(data.a, data.b); ans != data.c { t.Errorf("%d + %d expected %d,but %d got", data.a, data.b, data.c, ans) } }
zhangguofu@zhangguofudeMacBook-Pro add (master) $ go test -coverprofile=c.out --- FAIL: TestAdd (0.00s) add_test.go:20: 50 + 5 expected 5,but 55 got FAIL coverage: 33.3% of statements exit status 1 FAIL goapp/src/learngo/add 0.502s zhangguofu@zhangguofudeMacBook-Pro add (master) $ ls add.go add_test.go c.out zhangguofu@zhangguofudeMacBook-Pro add (master) $ cat c.out mode: set goapp/src/learngo/add/add.go:5.13,8.2 2 0 goapp/src/learngo/add/add.go:10.28,12.2 1 1
我们发现多了一个c.out 文件,但是里面的内容我们看不太懂,我们借助工具go tool cover ,查看代码覆盖的相关命令帮助
我们使用` go tool cover -html=c.out``,此时会打开一个html页面,上面标注了我们代码覆盖的情况
性能测试
我们通过一个获取最长不重复字符串函数来测试一下性能
函数代码 在add.go文件中
/** 最大字符串不重复 */ func Repeat(s string) int { //保持最大不重复串 lastOccur := make(map[string]int) start := 0 max := 0 for k, v := range []rune(s) { if index, ok := lastOccur[string(v)]; ok && start <= index { start = index + 1 } if max < k-start+1 { max = k - start + 1 } lastOccur[string(v)] = k } return max }
性能测试代码 在add_test.go文件中
func BenchmarkRepeat(b *testing.B) { str := "不经历风雨,怎么见彩虹?没有人能随随便便成功" data := struct { content string res int }{ str, 17, } for i := 0; i < b.N; i++ { if len := Repeat(data.content); len != 17 { b.Error("the program is wrong") } } }
zhangguofu@zhangguofudeMacBook-Pro add (master) $ go test -bench . -cpuprofile cpu.out goos: darwin goarch: amd64 pkg: goapp/src/learngo/add BenchmarkRepeat-8 1 1541179761 ns/op --- BENCH: BenchmarkRepeat-8 add_test.go:33: the len of str is 62914560 PASS ok goapp/src/learngo/add 2.077s zhangguofu@zhangguofudeMacBook-Pro add (master) $ ls add.go add.test add_test.go c.out cpu.out zhangguofu@zhangguofudeMacBook-Pro add (master) $ less cpu.out "cpu.out" may be a binary file. See it anyway?