如果测试是用户使用这套 API 的方式,可以对测试文件的包名加后缀 package exam_test
在*_test.go文件中,有三种类型的函数
测试函数 (Test)
基准测试函数(Bench)
示例函数 (Example)
测试函数
用于测试程序的一些逻辑行为是否正确,go test 命令会调用这些测试函数并报告测试结果。
1
2
3
import"testing"funcTestFuncName(t*testing.T){}
参考上面的格式, 以 Test 为函数名前缀,后面的FuncName首字母必须大写,参数类型必须是 *testing.T。
1
2
3
4
5
6
7
8
9
10
11
12
# 测试全部文件go test -v
# 测试单个文件go test -v cal_test.go cal.go
# 测试单个方法go test -v <file_name.go> -run TestAddUpper
# 测试以 French 和 Canal 为前缀的函数go test -v -run="French|Canal"# === RUN TestFrenchPalindrome# === RUN TestCanalPalindrome# 测试所有子目录go test -v ./...
funcTestIsPalindrome(t*testing.T){vartests=[]struct{inputstringwantbool}{{"",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},// non-palindrome
{"desserts",false},// semi-palindrome
}for_,test:=rangetests{ifgot:=IsPalindrome(test.input);got!=test.want{t.Errorf("IsPalindrome(%q) = %v",test.input,got)}}}funcIsPalindrome(strstring)bool{// ...
}