基礎測試
main.go
:
package main
import (
"fmt"
)
func main() {
fmt.Println(Sum(4,5))
}
func Sum(a, b int) int {
return a + b
}
main_test.go
:
package main
import (
"testing"
)
// Test methods start with `Test`
func TestSum(t *testing.T) {
got := Sum(1, 2)
want := 3
if got != want {
t.Errorf("Sum(1, 2) == %d, want %d", got, want)
}
}
要執行測試,只需使用 go test
命令:
$ go test
ok test_app 0.005s
使用 -v
標誌檢視每個測試的結果:
$ go test -v
=== RUN TestSum
--- PASS: TestSum (0.00s)
PASS
ok _/tmp 0.000s
使用路徑 ./...
遞迴測試子目錄:
$ go test -v ./...
ok github.com/me/project/dir1 0.008s
=== RUN TestSum
--- PASS: TestSum (0.00s)
PASS
ok github.com/me/project/dir2 0.008s
=== RUN TestDiff
--- PASS: TestDiff (0.00s)
PASS
執行特定測試:
如果有多個測試並且你想要執行特定測試,可以這樣做:
go test -v -run=<TestName> // will execute only test with this name
例:
go test -v run=TestSum