Loading...
Loading...
Test Go Gin APIs with httptest, table-driven tests, testcontainers. Use when writing tests for Gin handlers, services, middleware, or setting up integration and e2e tests.
npx skill4agent add henriqueatila/golang-gin-best-practices golang-gin-testingUserHandlerAuthHandlerUserRepositoryTestMain| Layer | Tool | Goal |
|---|---|---|
| Handler | | Verify HTTP contract (status codes, JSON shape) |
| Service | mock repository | Verify business logic, error mapping |
| Repository | testcontainers (real DB) | Verify SQL correctness |
| E2E | running server + real DB | Verify critical user flows end-to-end |
gin.SetMode(gin.TestMode)init()internal/testutil/NewTestRouter()gin.New()PerformRequest(t, router, method, path, body, headers)Content-TypeAssertJSON(t, w, &dst)BearerHeader(token)map[string]string{"Authorization": "Bearer " + token}testutil.PerformRequestw.CodecreateFngetByIDFn[]struct{ name, body, wantStatus }t.Run(tc.name, ...)t.Parallel()domain.UserRepositoryservice.NewUserService(repo, logger)errors.As(err, &appErr)*domain.AppErrorerrors.Isgo test -v -race -cover ./... # all tests
go test -v -race ./internal/handler/... # specific package
go test -v -race -cover -tags='!integration' ./... # unit only
go test -v -race -tags=integration ./internal/repository/... # integration only
go test -race -coverprofile=coverage.out ./... && go tool cover -html=coverage.outgo test -v -race-raceUserRepositoryreferences/clean-architecture.md