在Go語言中,進行單元測試非常簡單。你需要遵循以下步驟:
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
命令來運行測試。Go會自動發現并執行以"Test"為前綴的函數。你還可以使用-v
選項來輸出詳細的測試結果。$ go test -v
下面是一個完整的示例:
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)
}
}
運行測試:
$ go test -v
=== RUN TestMyFunction
--- PASS: TestMyFunction (0.00s)
PASS
ok mypackage 0.001s