編寫測試要求
- 文件名命名
xx_test.go
- 測試函數命名
TestXxx
開頭Xxx
首字母大寫 - 函數參數
*test.T
類型
需要測試的程序源碼
animal.go
package animal
import "fmt"
// Cat貓 結構體
type Cat struct {
Name string
Color string
Age uint
}
// 一個初始化Cat的入口函數
func NewCat(name,color string,age uint) *Cat {
return &Cat{name,color,age}
}
func (c *Cat) Sleeping() {
fmt.Println(c.Color,"Cat",c.Name,"is sleeping")
}
func (c *Cat) Eating() {
fmt.Println(c.Color,"Cat",c.Name,"is eating")
}
func (c *Cat) Print() {
fmt.Print(c)
}
單元測試
animal_test.go
package animal
import "testing"
func TestCat_Sleeping(t *testing.T) {
c := NewCat("Tom","blue",10)
c.Sleeping()
}
func TestCat_Eating(t *testing.T) {
c := NewCat("sinmigo","block",10)
c.Eating()
if c.Color == "white" {
t.Log("Eating 測試通過")
} else {
t.Error("Eating 測試不通過")
}
}
執行測試
go test -v -cover
--- PASS: TestCat_Sleeping (0.00s)
=== RUN TestCat_Eating
block Cat sinmigo is eating
TestCat_Eating: animal_test.go:16: Eating 測試不通過
--- FAIL: TestCat_Eating (0.00s)
FAIL
coverage: 75.0% of statements
exit status 1
FAIL animal 1.898s
性能測試
animal_test.go
// 性能測試
func BenchmarkCat_Eating(b *testing.B) {
c := NewCat("Tom","blue",10)
for i :=0;i<b.N; i++ {
c.Eating()
}
}
執行
go test -bench=.
blue Cat Tom is sleeping
block Cat sinmigo is eating
goos: windows
goarch: amd64
pkg: animal
BenchmarkCat_Eating-8 1000000000 0.306 ns/op
PASS
ok animal 3.062s