单元测试
原创大约 2 分钟
通常需要将package
命名为main
,并且要在main()
方法中才能运行代码,但对于单元测试来说这两个条件都不需要。
只需要按照命名约定,Go编译器就可以识别并执行单元测试方法。
// 在包目录中,所有以 _test.go为后缀的源码文件都会被 go test 执行
// 有四类单元测试:
// 1. 以 Test 开头,以*testing.T为参数,执行功能测试
// 2. 以 Benchmark 开头,以*testing.B为参数,执行性能测试
// 3. 以 Example 开头,以*testing.T为参数,执行示例测试
// 4. 以 Fuzz 开头,以*testing.F为参数,执行模糊测试
package unittest
import (
"fmt"
"github.com/stretchr/testify/assert"
"strconv"
"strings"
"testing"
)
func TestAdd(t *testing.T) {
assert.Equal(t, 3, add(1, 2))
}
// go test 命令执行单元测试
// 可以cd到需要执行单元测试的目录中,例如:
// cd /home/work/workspace-go/learngo/chapter05/unittest
// 执行命令:
// go test
// 结果如下:
// PASS
// ok learngo/chapter05/unittest 0.402s
func TestAddByError(t *testing.T) {
result := add(1, 2)
if result != 3 {
t.Error("add(1, 2) 不等于 3")
} else {
t.Log("测试成功")
}
}
// 跳过耗时的单元测试
// 对于执行时间过长的单元测试,可以使用 go test -short 跳过耗时的单元测试
func TestAddBySkip(t *testing.T) {
if testing.Short() {
t.Skip("跳过耗时的单元测试")
}
result := add(1, 2)
if result != 3 {
t.Error("add(1, 2) 不等于 3")
} else {
t.Log("测试成功")
}
}
// 基于表格对测试数据进行管理
func TestAddByTable(t *testing.T) {
// 基于结构体切片进行测试数据管理
testData := []struct {
a int
b int
result int
}{
{1, 2, 3},
{2, 2, 4},
{3, 2, 5},
}
for _, data := range testData {
// assert.Equal(t, data.result, add(data.a, data.b))
re := add(data.a, data.b)
if re != data.result {
t.Errorf("add(%d, %d) 不等于 %d", data.a, data.b, data.result)
} else {
t.Log("测试成功")
}
}
}
// 执行benchmark性能测试
func BenchmarkAdd(b *testing.B) {
var x, y, z = 123, 456, 579
// 循环执行add(1, 2),这里的 b.N 可以通过命令行指定
for i := 0; i < b.N; i++ {
if result := add(x, y); result != z {
b.Logf("add(%d, %d) 不等于 %d", x, y, z)
}
}
}
const numbers = 10000
// 测试字符串拼接性能之Springf
func BenchmarkStringSpringf(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var str string
for j := 0; j < numbers; j++ {
str = fmt.Sprintf("%s %d", str, j)
}
}
b.StopTimer()
}
// 测试字符串拼接性能之Add
func BenchmarkStringAdd(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var str string
for j := 0; j < numbers; j++ {
str += strconv.Itoa(j)
}
}
b.StopTimer()
}
// 测试字符串拼接性能之Builder
func BenchmarkStringBuilder(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var builder strings.Builder
for j := 0; j < numbers; j++ {
builder.WriteString(strconv.Itoa(j))
}
_ = builder.String()
}
b.StopTimer()
}
// 在代码目录下执行命令:go test -bench=".*"
// 即可看到结果
感谢支持
更多内容,请移步《超级个体》。