在Go語言中,進(jìn)行單元測試非常簡單。你需要遵循以下步驟:
package mypackage
import (
"testing"
)
func TestMyFunction(t *testing.T) {
// 測試代碼
}
func TestMyFunction(t *testing.T) {
result := MyFunction()
if result != expected {
t.Errorf("MyFunction() returned %v, expected %v", result, expected)
}
}
go test
命令來運(yùn)行測試。Go會(huì)自動(dòng)發(fā)現(xiàn)并執(zhí)行以"Test"為前綴的函數(shù)。你還可以使用-v
選項(xiàng)來輸出詳細(xì)的測試結(jié)果。$ go test -v
下面是一個(gè)完整的示例:
package mypackage
import (
"testing"
)
func MyFunction() int {
return 42
}
func TestMyFunction(t *testing.T) {
result := MyFunction()
expected := 42
if result != expected {
t.Errorf("MyFunction() returned %v, expected %v", result, expected)
}
}
運(yùn)行測試:
$ go test -v
=== RUN TestMyFunction
--- PASS: TestMyFunction (0.00s)
PASS
ok mypackage 0.001s