1
单元测试
Go 内置了强大的测试框架。测试文件以 _test.go 结尾,测试函数以 Test 开头。
编写单元测试
go
1package main2 3import "testing"4 5func Add(a, b int) int {6 return a + b7}8 9func TestAdd(t *testing.T) {10 result := Add(2, 3)11 expected := 512 13 if result != expected {14 t.Errorf("Add(2, 3) = %d; want %d", result, expected)15 }16}17 18// 表驱动测试19func TestAddTableDriven(t *testing.T) {20 tests := []struct {21 name string22 a, b int23 expected int24 }{25 {"positive", 2, 3, 5},26 {"negative", -1, -2, -3},27 {"zero", 0, 0, 0},28 }29 30 for _, tt := range tests {31 t.Run(tt.name, func(t *testing.T) {32 result := Add(tt.a, tt.b)33 if result != tt.expected {34 t.Errorf("got %d, want %d", result, tt.expected)35 }36 })37 }38}