在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