Skip to content

测试 ​

分层测试策略,SQLite 临时库隔离,无外部依赖即可跑。

覆盖范围 ​

层范围工具
repository真实 SQLite + GORM,覆盖 CRUD/过滤/数据范围testutil.NewTestDB(t)
serviceSQLite 或 mock repo,覆盖业务编排testutil.NewTestDB(t)
handlerhttptest 端到端,打通鉴权→业务→持久化net/http/httptest
pkg纯函数包,覆盖核心逻辑标准测试

当前覆盖率 ​

包覆盖率
pkg/datascope100%
pkg/csvutil100%
pkg/pagination87.5%
pkg/audit65.7%
repository53.2%
service53.9%
middleware25.4%
handler6.3%(模式已建立,渐进补齐)

跑测试 ​

bash
make server-test         # 全量
make server-cover        # 生成覆盖率报告 cover.html

写测试的模式 ​

Repository / Service ​

go
func TestFooRepo_CRUD(t *testing.T) {
    db := testutil.NewTestDB(t)   // SQLite 临时库 + AutoMigrate
    repo := NewFooRepository(db)
    // ... 走真实 GORM,隔离 MySQL
}

Handler 集成测试 ​

go
func newAuthTestServer(t *testing.T) (*gin.Engine, *service.AuthService) {
    db := testutil.NewTestDB(t)
    audit.Register(db)
    // ... 装配 repo→service→handler→gin engine
}

func TestLogin(t *testing.T) {
    r, _ := newAuthTestServer(t)
    w := doJSON(t, r, POST, "/api/auth/sessions",
        LoginRequest{Username: "admin", Password: "123456"})
    assert.Equal(t, 200, w.Code)
}

参考 handler/auth_integration_test.go 与 handler/user_integration_test.go。

CI 门禁 ​

GitHub Actions(.github/workflows/ci.yml)在每次 push/PR 跑: golangci-lint → swagger 生成 → go vet → go test -race → build。本地复现:make server-ci。

基于 MIT 协议发布