Go test工具链
2018-08-21 本文已影响85人
会长__
1.简介
go test命令用于对Go语言编写的程序进行测试。这种测试是以代码包为单位的。
image.png
2. 简单介绍
package main
// 文件名以_test.go 结尾
import (
"testing"
"fmt"
)
// 方法名必须已Test开头,参数必须为*testing.T
func TestPrint(t *testing.T) {
t.SkipNow() // 跳过此Test函数,只能放到第一行
res := Print1to20()
fmt.Println("hey")
if res != 210 {
t.Errorf("ERR")
}
}
// 1-20的和
func Print1to20() (sum int) {
for a := 1; a<=20; a++ {
sum += a
}
return sum
}
// 这个不会执行
func testPrint(t *testing.T) {
fmt.Println("I did it")
}
执行 (根据注释中的内容做相应的调整执行)

3.更合理的写法

package main
// 文件名以_test.go 结尾
import (
"testing"
"fmt"
)
// 子test
func testPrint(t *testing.T) {
res := Print1to20()
fmt.Println("hey")
if res != 210 {
t.Errorf("ERR")
}
}
// 子test
func testPrint2(t *testing.T) {
res := Print1to20()
fmt.Println("hello")
if res != 211 {
t.Errorf("2 ERR")
}
}
// 1-20的和
func Print1to20() (sum int) {
for a := 1; a<=20; a++ {
sum += a
}
return sum
}
func TestAll(t *testing.T) {
t.Run("testPrint", testPrint)
t.Run("testPrint2", testPrint2)
}
func TestMain(m *testing.M) {
fmt.Println("Test begins....")
m.Run() // 如果不加这句,只会执行Main
}
结果
