在練習(xí) 9.4 中你寫了一個叫 main_oddeven.go 的程序用來測試前 100 個整數(shù)是否是偶數(shù)。這個函數(shù)屬于 even 包。
下面是一種可能的方案:
示例 13.7 even_main.go:
package main
import (
"fmt"
"even/even"
)
func main() {
for i:=0; i<=100; i++ {
fmt.Printf("Is the integer %d even? %v\n", i, even.Even(i))
}
}
上面使用了 even.go 中的 even 包:
示例 13.8 even/even.go:
package even
func Even(i int) bool { // Exported function
return i%2 == 0
}
func Odd(i int) bool { // Exported function
return i%2 != 0
}
在 even 包的路徑下,我們創(chuàng)建一個名為 oddeven_test.go 的測試程序:
示例 13.9 even/oddeven_test.go:
package even
import "testing"
func TestEven(t *testing.T) {
if !Even(10) {
t.Log(" 10 must be even!")
t.Fail()
}
if Even(7) {
t.Log(" 7 is not even!")
t.Fail()
}
}
func TestOdd(t *testing.T) {
if !Odd(11) {
t.Log(" 11 must be odd!")
t.Fail()
}
if Odd(10) {
t.Log(" 10 is not odd!")
t.Fail()
}
}
由于測試需要具體的輸入用例且不可能測試到所有的用例(非常像一個無窮的數(shù)),所以我們必須對要使用的測試用例思考再三。
至少應(yīng)該包括:
可以直接執(zhí)行 go install 安裝 even 或者創(chuàng)建一個 以下內(nèi)容的 Makefile:
include $(GOROOT)/src/Make.inc
TARG=even
GOFILES=\
even.go\
include $(GOROOT)/src/Make.pkg
然后執(zhí)行 make(或 gomake)命令來構(gòu)建歸檔文件 even.a
測試代碼不能在 GOFILES 參數(shù)中引用,因為我們不希望生成的程序中有測試代碼。如果包含了測試代碼,go test 會給出錯誤提示!go test 會生成一個單獨的包含測試代碼的 _test 程序。
現(xiàn)在我們可以用命令:go test(或 make test)來測試 even 包。
因為示例 13.5 中的測試函數(shù)不會調(diào)用 t.Log 和 t.Fail,所以會得到一個 PASS 的結(jié)果。在這個簡單例子中一切都正常執(zhí)行。
為了看到失敗時的輸出,把函數(shù) TestEven 改為:
func TestEven(t *testing.T) {
if Even(10) {
t.Log("Everything OK: 10 is even, just a test to see failed output!")
t.Fail()
}
}
現(xiàn)在會調(diào)用 t.Log 和 t.Fail,得到的結(jié)果如下:
--- FAIL: even.TestEven (0.00 seconds)
Everything OK: 10 is even, just a test to see failed output!
FAIL
練習(xí) 13.4:string_reverse_test.go
為練習(xí) 7.11 string_reverse.go 寫一個單元測試。
把 string_reverse 放到自己的包 strev 中,只包含一個可導(dǎo)出函數(shù) reverse。
實現(xiàn)并測試它。