目录
一、功能测试
1.0 知识点
func TestXXX(t *testing.T)
go test -v
1.1 代码
文件:MyTest.go
package main
import (
"fmt"
)
func Add(a, b int) int {
return a + b
}
func main() {
a := 10
b := 20
fmt.Println("sum:", Add(a,b))
}文件:MyTest_test.go
package main
import (
"fmt"
"testing"
)
func TestAdd(t *testing.T) {
a := 5
b := 6
if Add(a, b) != 11 {
fmt.Println("error")
t.Error("run error")
}
fmt.Println("success")
}1.2 执行及结果
运行命令:
go test
go test -v
go test MyTest_test.go MyTest.go -v
go test . -v
go test ./... -v
go test *.go -v
运行结果:

二、性能测试
2.0 知识点
func BenchmarkXXX(b *testing.B)
go test -v -bench=.
2.1 代码
文件:MyTest.go(同上面)
文件:MyTest_test.go
package main
import (
"fmt"
"testing"
)
func BenchmarkAdd(b *testing.B) {
a := 5
c := 6
if Add(a, c) != 11 {
fmt.Println("error")
b.Error("run error")
}
fmt.Println("success")
}2.2 运行及结果
运行命令:
go test -bench=.
go test -v -bench=.
运行结果:运行了1000000000次,平均每次运行时间0.000008 ns

三、TestMain
3.0 知识点
func TestMain(m *testing.M)
1.TestMain会比所有的TestXXX、BenchmarkXXX函数最先执行。
2.只有当在TestMain函数中调用m.Run()才会执行其他的TestXXX、BenchmarkXXX
3.1 代码
文件:MyTest.go(同上面)
文件:MyTest_test.go
package main
import (
"fmt"
"testing"
)
func BenchmarkAdd(b *testing.B) {
a := 5
c := 6
if Add(a, c) != 11 {
fmt.Println("error")
b.Error("run error")
}
fmt.Println("success")
}
func TestMain(m *testing.M) {
fmt.Println("-----start-----")
m.Run()
fmt.Println("-----end-----")
}3.2 运行及结果
运行命令:
go test -bench=.
go test -v -bench=.
运行结果:

版权声明:本文为kanguolaikanguolaik原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。