package main
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
expected := 5
if result != expected {
t.Errorf("Add(2, 3) = %d; want %d", result, expected)
}
}
// 表驱动测试
func TestAddTable(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive", 2, 3, 5},
{"negative", -1, -1, -2},
{"zero", 0, 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("got %d, want %d", result, tt.expected)
}
})
}
}type UserRepository interface {
GetUser(id string) (*User, error)
}
type MockUserRepository struct {
GetUserFunc func(id string) (*User, error)
}
func (m *MockUserRepository) GetUser(id string) (*User, error) {
return m.GetUserFunc(id)
}
func TestUserService(t *testing.T) {
mockRepo := &MockUserRepository{
GetUserFunc: func(id string) (*User, error) {
return &User{ID: id, Name: "Test"}, nil
},
}
service := NewUserService(mockRepo)
user, err := service.GetUser("123")
if err != nil || user.Name != "Test" {
t.Error("Test failed")
}
}# wrk
wrk -t4 -c100 -d30s http://localhost:8080/api/test
# Go benchmark
go test -bench=. -benchmem关键要点:
- ✅ 单元测试覆盖核心逻辑
- ✅ Mock隔离外部依赖
- ✅ 集成测试验证流程
- ✅ 压力测试评估性能