micro-bundle/internal/testutil/db.go
cjy 590f0dedd6 test: 为 taskDao 与 taskLogic 添加单元测试
新增 internal/testutil/db.go,基于 DATA-DOG/go-sqlmock 提供
SetupTaskBenchDB 帮助函数,把 mock 出来的 *gorm.DB 挂到
app.ModuleClients.TaskBenchDB 上,方便 dao / logic 层单测。
SQL 匹配使用 QueryMatcherRegexp,避免对 gorm 生成的 SQL 字面量
(字段顺序、占位符数量等)过度耦合。

- internal/dao/taskDao_test.go:覆盖 GetPendingTaskLayout 等
  DAO 方法的 SQL 行为与错误分支。
- internal/logic/taskLogic_test.go:覆盖 CreateTaskWorkLog
  的入参范围校验分支。

go.mod / go.sum:
- 新增直接依赖 github.com/DATA-DOG/go-sqlmock v1.5.2、
  github.com/stretchr/testify v1.11.1;
- 调整 google/uuid、robfig/cron/v3、satori/go.uuid 为直接依赖。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 15:21:03 +08:00

48 lines
1.3 KiB
Go

package testutil
import (
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"micro-bundle/pkg/app"
"micro-bundle/pkg/db"
)
// SetupTaskBenchDB 创建一个 sqlmock 驱动的 *gorm.DB,挂到 app.ModuleClients.TaskBenchDB。
// 返回的 sqlmock 用于在测试中声明期望 SQL,cleanup 自动还原全局单例。
//
// 使用 QueryMatcherRegexp 匹配,SQL 文本作为正则匹配(支持 .* 等),
// 避免对 gorm 生成 SQL 的细节(字段顺序、占位符数量)过度耦合。
func SetupTaskBenchDB(t *testing.T) sqlmock.Sqlmock {
t.Helper()
mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
require.NoError(t, err)
gormDB, err := gorm.Open(mysql.New(mysql.Config{
Conn: mockDB,
SkipInitializeWithVersion: true,
}), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
DisableForeignKeyConstraintWhenMigrating: true,
})
require.NoError(t, err)
original := app.ModuleClients
app.ModuleClients = &app.App{
Lg: zap.NewNop(),
TaskBenchDB: &db.TaskBenchDB{DB: gormDB},
}
t.Cleanup(func() { app.ModuleClients = original })
return mock
}