引言
单元测试是软件开发的重要组成部分,它帮助开发者验证代码的功能是否按预期工作。
测试文件结构
- 命名约定:
- 测试文件名以 _test.go 结尾。
- 测试函数名以 Test 开头。
- 示例,当前测试文件名 mypackage_test.go:
package mypackage
import "testing"
func TestAdd(t *testing.T) {
// 测试代码
}编写测试用例
- 基本测试函数:
- 使用 t.Errorf 或 t.Fatal 来报告失败。
- 示例:
func TestAdd(t *testing.T) {
if sum := add(2, 3); sum != 5 {
t.Errorf("Expected 5 but got %d", sum)
}
}- 测试表格:
- 使用表格来组织多组测试数据。
- 示例:
type testCase struct {
x, y, expected int
}
func TestAdd(t *testing.T) {
tests := []testCase{
{2, 3, 5},
{-1, -1, -2},
{0, 0, 0},
}
for _, tc := range tests {
if sum := add(tc.x, tc.y); sum != tc.expected {
t.Errorf("add(%d, %d) = %d; want %d", tc.x, tc.y, sum, tc.expected)
}
}
}断言库
- 使用 testing 包:
- testing 包提供了基本的断言功能。
- 示例:
func TestAdd(t *testing.T) {
if sum := add(2, 3); sum != 5 {
t.Errorf("Expected 5 but got %d", sum)
}
}- 使用第三方断言库:
- github.com/stretchr/testify/assert 提供了更丰富的断言功能。
- 示例:
import "github.com/stretchr/testify/assert"
func TestAdd(t *testing.T) {
assert.Equal(t, 5, add(2, 3), "Expected 5 but got %d")
}基准测试
- 基本用法:
- 使用 Benchmark 前缀命名基准测试函数。
- 示例:
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
add(2, 3)
}
}- 测量性能:
- 使用 b.ResetTimer() 和 b.StartTimer() 控制计时器。
- 示例:
func BenchmarkAdd(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
b.StartTimer()
add(2, 3)
b.StopTimer()
}
}编码实践
// 目录结构:
// project/
// ├── mypackage.go
// ├── mypackage_test.go
// └── go.mod
// 当前文件名:mypackage_test.go
package mypackage
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func add(x, y int) int {
return x + y
}
func TestAdd(t *testing.T) {
type testCase struct {
x, y, expected int
}
tests := []testCase{
{2, 3, 5},
{-1, -1, -2},
{0, 0, 0},
}
for _, tc := range tests {
t.Run(fmt.Sprintf("%d+%d", tc.x, tc.y), func(t *testing.T) {
assert.Equal(t, tc.expected, add(tc.x, tc.y))
})
}
}
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
add(2, 3)
}
}运行测试
- 命令行工具:
- 使用 go test 命令运行测试。
- 示例:
go test ./...- 指定测试:
- 使用 -run 标志指定要运行的测试。
- 示例:
go test ./... -run TestAdd- 忽略测试:
- 使用 -short 标志忽略基准测试。
- 示例:
go test ./... -short