Gopl 第十一章 测试

说明

本文为GOPL第十一章学习笔记

测试基础

文件名: 以_test.go 结尾
依赖包: testing
功能函数名: Test开头后接大写字母(若后接小写字母将无法识别)
测试函数模板:func TestFunc(t *testing.T){}
命令行:

* go test
* go test -v  //逐个函数测试
* go test -v -run="pattern"//只测试函数名匹配的函数

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//word.go
package word

import "unicode"

func Ispalindrome(s string ) bool {
var letters []rune
for _, r := range s{
if unicode.IsLetter(r){
letters = append(letters,unicode.ToLower(r))
}
}
for i := range letters {
if letters[i] != letters[len(letters)-1-i] {
return false
}
}
return true
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//word_test.go
package word

import "testing"

func TestPalindrome(t *testing.T) {
var tests = []struct {
input string
want bool
}{
{"", true},
{"a", true},
{"aa", true},
{"ab", false},
{"kayak", true},
{"detartrated", true},
{"A man, a plan, a canal: Panama", true},
{"Evil I did dwell; lewd did I live.", true},
{"Able was I ere I saw Elba", true},
{"été", true},
{"Et se resservir, ivresse reste.", true},
{"palindrome", false},
{"desserts", false},
}
for _, test := range tests{
if got := Ispalindrome(test.input); got != test.want{
t.Errorf("IaPalindrome(%q) = %v,want %v",test.input,got,test.want)
}
}
}

随机测试

通过测试用例随机化来扩展测试的覆盖范围

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
func randomPalindrome(rng *rand.Rand) string{
n := rng.Intn(25)
runes := make([]rune,n)
for i :=0;i<(n+1)/2;i++{
r := rune(rng.Intn(0x1000))
runes[i] = r
runes[n-1-i] =r
}
return string(runes)
}
func randomUnPalindrome(rng *rand.Rand) string{
n := rng.Intn(25)
runes := make([]rune,n)
for i :=0;i< n ;i++{
r := rune(rng.Intn(0x1000))
runes[i] = r
}
str := string(runes)
if !Ispalindrome(str){
return str
}
return randomUnPalindrome(rng)
}


func TestRandomPalindrome(t *testing.T){
seed := time.Now().UTC().UnixNano()
t.Logf("Random seed: %d",seed)
rng := rand.New(rand.NewSource(seed))
for i:=0;i<1000;i++{
p := randomPalindrome(rng)
if !Ispalindrome(p){
t.Errorf("IsPalindrome(%q) = false",p)
}
}
}
func TestRandomUnPalindrome(t *testing.T){
seed := time.Now().UTC().UnixNano()
t.Logf("Random seed: %d",seed)
rng := rand.New(rand.NewSource(seed))
for i:=0;i<1000;i++{
p := randomUnPalindrome(rng)
if Ispalindrome(p){
t.Errorf("IsPalindrome(%q) = true",p)
}
}
}