Go程序开发过程中免不了要对所写的单个业务方法进行单元测试,Go提供了 “testing” 包可以实现单元测试用例的编写,不过想要正确编写单元测试需要注意以下三点:
以下是我写的一个unit_test.go单元测试文件
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
如对本文有疑问, 点击进行留言回复!!
VSCode1.4 搭建Golang的开发调试环境(遇到很多问题)
网友评论