Skip to content

Latest commit

 

History

History
104 lines (77 loc) · 1.98 KB

File metadata and controls

104 lines (77 loc) · 1.98 KB

10.1 测试体系建设

📍 导航返回目录 | 下一节:代码质量


单元测试(Go)

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)
            }
        })
    }
}

Mock测试

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隔离外部依赖
  • ✅ 集成测试验证流程
  • ✅ 压力测试评估性能

⏮️ 返回目录 | ⏭️ 下一节:代码质量