概述
Go 语言中自带有一个轻量级的测试框架 testing 和自带的 go test 命令来实现单元测试和性能测试,testing 框架和其他语言中的测试框架类似,可以基于这个框架写针对相应函数的测试用例,也可以基于该框架写相应的压力测试用例。通过单元测试,可以解决如下问题:
- 确保每个函数是可运行,并且运行结果是正确的。
- 确保写出来的代码性能是好的。
- 单元测试能及时的发现程序设计或实现的逻辑错误,使问题及早暴露,便于问题的定位解决,而性能测试的重点在于发现程序设计上的一些问题,让程序能够在高并发的情况下还能保持稳定。
单元测试
函数规则:
- 函数名: TestXxxx,以Test为前缀。Xxxx 以大写字母开头
- 参数类型: *testing.T
func TestXxxx(t *testing.T){...}
运行指令:
- cmd > go test [如果运行正确,无日志,错误时,会输出日志]
- cmd > go test -v [运行正确或是错误,都输出日志]
测试用例:
D:\GoWork\src\tests\demo_test.go
package tests
import "testing"
func getSum(a, b int) int {
return a + b
}
func TestGetSum(t *testing.T) {
res := getSum(1, 2)
if res != 3 {
t.Fatal("test getSum error")
}
t.Logf("test getSum success")
}
D:\GoWork\src\tests>go test demo_test.go
ok command-line-arguments 0.695s
D:\GoWork\src\tests>go test -v demo_test.go
=== RUN TestGetSum
demo_test.go:14: test getSum success
--- PASS: TestGetSum (0.00s)
PASS
ok command-line-arguments 0.723s
使用总结:
- 一个测试用例文件中,可以有多个测试用例函数。
- 当出现错误时,可以使用 t.Fatalf 来格式化输出错误信息,并退出程序。
- t.Logf 方法可以输出相应的日志。
- 测试用例函数,并没有放在 main 函数中,也执行了,这就是测试用例的方便之处。
- PASS 表示测试用例运行成功,FAIL表示测试用例运行失败。
- 测试单个文件,一定要带上被测试的原文件
go test -v demo_test.go demo.go
- 测试单个方法
go test -v -test.run TestGetSum
go test 常用参数:
参数 | 描述 |
---|---|
-cpu | 设置测试最大 cpu 逻辑数(也就是 GPM 中 P, 最大并行执行的 gorouting 数量, 默认等于 cpu 核数) |
-count | 设置执行测试函数的次数, 默认为 1 |
-run | 执行功能测试函数, 支持正则匹配, 可以选择测试函数或者测试文件来仅测试单个函数或者单个文件 |
-bench | 执行基准测试函数, 支持正在匹配 |
-benchtime | 基准测试最大探索时间上限 |
-parallel | 设置同一个被测试代码包中的功能测试函数的最大并发执行数 |
-v | 是展示测试过程信息 |
基准测试
函数规则:
- 函数名: BenchmarkXxxx, 以 Benchmark 为前缀。Xxxx 以大写字母开头
- 参数类型: *testing.B
func BenchmarkXxxx(b *testing.B){...}
测试用例:
D:\GoWork\src\tests\demo_test.go
package tests
import "testing"
func getSum(a, b int) int {
return a + b
}
func BenchmarkGetSum(b *testing.B) {
for i := 0; i < b.N; i++ {
getSum(1, 2)
}
}
D:\GoWork\src\tests>go test -bench=. -run=^$
goos: windows
goarch: amd64
pkg: tests
cpu: Intel(R) Core(TM) i5-7400 CPU @ 3.00GHz
BenchmarkGetSum-4 1000000000 0.3197 ns/op
PASS
ok tests 1.026s
测试结果说明:
- -4 表示 4个逻辑 cpu 个数
- 1000000000表示执行了 1000000000次
- 0.3197 ns/op 每次操作耗时
- 1.026s 是总时长
性能测试函数计时器:
当性能测试函数中有一些额外的初始化操作时,可以通过启停计时器来屏蔽这些操作对最终性能测试的影响。
package tests
import (
"testing"
"time"
)
func getSum(a, b int) int {
return a + b
}
func BenchmarkGetSum(b *testing.B) {
time.Sleep(10 * time.Second)
for i := 0; i < b.N; i++ {
getSum(1, 2)
}
}
D:\GoWork\src\tests>go test -bench=.
goos: windows
goarch: amd64
pkg: tests
cpu: Intel(R) Core(TM) i5-7400 CPU @ 3.00GHz
BenchmarkGetSum-4 1 10007145700 ns/op
PASS
ok tests 10.710s
单个测试函数耗时为 10007145700 ns/op,同时我们也可以看到,这个函数执行一次就已经达到了最大上限时间。
加上时间计数器:
package tests
import (
"testing"
"time"
)
func getSum(a, b int) int {
return a + b
}
func BenchmarkGetSum(b *testing.B) {
b.StopTimer()
time.Sleep(10 * time.Second)
for i := 0; i < b.N; i++ {
getSum(1, 2)
}
}
D:\GoWork\src\tests>go test -bench=.
goos: windows
goarch: amd64
pkg: tests
cpu: Intel(R) Core(TM) i5-7400 CPU @ 3.00GHz
BenchmarkGetSum-4 1000000000
PASS
ok tests 61.290s
使用总结:
对于 b.N 参数而言,test 命令先会尝试设置为1,之后执行函数。如果测试函数没有达到执行上限的话,test 函数会增大,之后再次执行测试函数,如此往复,直到执行时间大于或者等于上限时间为止。 上限时间可以使用 -benchtime
设定。
应用实例
- 编写一个 Monster 结构图,字段 Name,Age,Skill。
- 给 Monster 绑定方法 Store,可以将一个 Monster 变量(对象),序列化后保存到文件中。
- 给 Monster 绑定方法 ReStore,可以将一个序列化的 Monster 从文件中读取,并反序列化为 Monster 休想,检查反序列化,名字正确。
- 编程测试用例文件 store_test.go,编写测试用例函数 TestStore 和 TestRestore 进行测试。
D:\GoWork\src\monster\monster.go
package monster
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type Monster struct {
Name string
Age int
Skill string
}
// 给 Monster 绑定方法 Store,可以将一个 Monster 变量(对象),序列化后保存到文件中
func (this *Monster) Store() bool {
// 先序列化
data, err := json.Marshal(this)
if err != nil {
fmt.Println("marshal err =", err)
return false
}
// 保存到文件
filePath := "d:/monster.ser"
err = ioutil.WriteFile(filePath, data, 0666)
if err != nil {
fmt.Println("write file err =", err)
return false
}
return true
}
// 给 Monster 绑定方法 ReStore,可以将一个序列化的 Monster,从文件中读取, 并反序列化为 Monster对象,检查反序列化,名字正确
func (this *Monster) ReStore() bool {
// 1.先从文件中,读取序列化的字符串
filePath := "d:/monster.ser"
data, err := ioutil.ReadFile(filePath)
if err != nil {
fmt.Println("ReadFile err =", err)
return false
}
// 2.使用读取到 data []byte ,对反序列化
err = json.Unmarshal(data, this)
if err != nil {
fmt.Println("UnMarshal err =", err)
return false
}
return true
}
D:\GoWork\src\monster\monster_test.go
package monster
import "testing"
// 测试用例,测试 Store 方法
func TestStore(t *testing.T) {
// 先创建一个 Monster实例
monster := &Monster{
Name: "红孩儿",
Age: 10,
Skill: "吐火.",
}
res := monster.Store()
if !res {
t.Fatalf("monster.Store()错误,希望为=%v实际为=%v", true, res)
}
t.Logf("monster.Store()测试成功!")
}
func TestReStore(t *testing.T) {
// 测试数据是很多,测试很多次,才确定函数,模块..
// 先创建一个 Monster 实例,不需要指定字段的值
var monster = &Monster{}
res := monster.ReStore()
if !res {
t.Fatalf("monster.ReStore()错误,希望为=%v实际为=%v", true, res)
}
// 进一步判断
if monster.Name != "红孩儿" {
t.Fatalf("monster.ReStore()错误,希望为=%v实际为=%v", "红孩儿", monster.Name)
}
t.Logf("monster.ReStore()测试成功!")
}
D:\GoWork\src\monster>go test -v
=== RUN TestStore
monster_test.go:17: monster.Store()测试成功!
--- PASS: TestStore (0.00s)
=== RUN TestReStore
monster_test.go:32: monster.ReStore()测试成功!
--- PASS: TestReStore (0.00s)
PASS
ok monster 0.726s