testing 包用于go的单元测试。
引入:
import "testing"
一、测试规则
要创建测试文件,需要将文件名设置为 xxx_test.go ,结尾必须是 _test.go 。
测试文件中的,结构必须为如下形式:
func TestXXX(t *testing.T) {...}func BenchmarkXXX(t *testing.B) {...}
- 单元测试方法必须以
Test开头,压力测试方法必须以Benchmark开头 - 单元测试参数必须是
(t *testing.T),性能测试参数必须是(t *testing.B)
执行测试:
go test 测试文件名
二、单元(功能)测试
比如有如下一个程序:demo.go
package test
func GetArea(weight int, height int) int {
return weight * height
}
demo_test.go
package test
import "testing"
func TestGetArea(t *testing.T) {
area := GetArea(40, 50)
if area != 2000 {
t.Error("测试失败")
}
}
执行完单元测试输出:
三、性能(压力)测试
还是上面那个例子:
func BenchmarkGetArea(t *testing.B) {
for i := 0; i < t.N; i++ {
GetArea(40, 50)
}
}
在PyCharm左侧,可以看到运行按钮,直接点击即可开始测试。
执行完压力测试输出:
