Go单元测试注意事项及测试单个方法和整个文件的命令
Go程序开发过程中免不了要对所写的单个业务方法进行单元测试,Go提供了 “testing” 包可以实现单元测试用例的编写,不过想要正确编写单元测试需要注意以下三点:
- Go文件名必须以 "_test" 结尾
- Go文件中的方法名必须以 “Test” 打头
- 方法的形参必须为 (t *testing.T)
以下是我写的一个unit_test.go单元测试文件
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。package test
import (
"testing"
"fmt"
)
// 测试helloworld
func TestHelloWorld(t *testing.T) {
fmt.Println("This is a HelloWorld unit test")
}
// 测试控制台打印
func TestPrint(t *testing.T) {
fmt.Println("This is a Print unit test")
}
测试整个文件命令如下:
$ go test -v unit_test.go
结果如下:
=== RUN TestHelloWorld
This is a HelloWorld unit test
--- PASS: TestHelloWorld (0.00s)
=== RUN TestPrint
This is a Print unit test
--- PASS: TestPrint (0.00s)
PASS
ok command-line-arguments 0.005s
测试单个方法命令如下:
$ go test -v unit_test.go -test.run TestHelloWorld
结果如下:
=== RUN TestHelloWorld
This is a HelloWorld unit test
--- PASS: TestHelloWorld (0.00s)
PASS
ok command-line-arguments 0.003s
更多精彩