SuperAPI AI 工具集

golang-gin-testing

测试与质量

查看项目

更新于 10-15 22:12

技能介绍

用途:为 Go Gin API 编写测试,覆盖 handler、service、middleware 与集成、端到端场景。

主要能力:按层组织测试——handler 用 httptest 加 mock service 验证 HTTP 契约(状态码、JSON 结构);service 用 mock repository 验证业务逻辑与错误映射;repository 用 testcontainers 连真实 PostgreSQL 验证 SQL;e2e 用运行中的服务加真实数据库验证关键流程。支持表驱动测试、JWT 中间件隔离测试、TestMain 共享测试基础设施,以及基准、模糊、golden 文件与 k6、Vegeta 负载测试参考。

使用方式:在测试 init() 中调用 gin.SetMode(gin.TestMode) 抑制调试输出;使用 internal/testutil 中的 NewTestRouter、PerformRequest、AssertJSON、BearerHeader 等辅助函数;mock 通过函数字段实现接口;用 errors.As 检查 *domain.AppError。常用命令:go test -v -race -cover ./...;go test -v -race -cover -tags='!integration' ./...;go test -v -race -tags=integration ./internal/repository/...;go test -race -coverprofile=coverage.out ./... && go tool cover -html=coverage.out。

适用场景:为 Gin handler、service、middleware 编写单元测试,搭建 testcontainers 集成测试,编写注册到 CRUD 的 e2e 流程测试,以及性能与回归测试。

限制:不涉及 API 实现、认证、数据库查询与部署,这些分别由 golang-gin-api、golang-gin-auth、golang-gin-database、golang-gin-deploy 处理;具体依赖版本、配置细节与完整代码示例需查阅其参考文件或官方文档,资料未提供。