Golang Testing
Priority: P0 (CRITICAL)
Implementation Workflow
- Write failing test first — Follow Red-Green-Refactor TDD workflow.
- Use table-driven tests — Define test cases as a slice of structs; iterate with
t.Run(). - Mock via interfaces — Use DI and interfaces. Prefer
mockeryfor auto-generated mocks or manual mocks for simple cases. - Run parallel — Use
t.Parallel()for non-sequential tests to speed up CI. - Clean up resources — Use
t.Cleanup()to reset state or release DB/file resources. - Check coverage — Aim for >80% line coverage. Run
go test -coverto audit.
See table-driven test examples
Tools
- Stdlib:
testingpackage is usually enough. - Testify: Assertions (
assert,require) and mocks. - Mockery: Auto-generate mocks for interfaces.
- GoMock: Popular mocking framework alternative.
Naming
- Test file:
*_test.go - Test function:
func TestName(t *testing.T) - Example function:
func ExampleName()
Anti-Patterns
- ❌
assertinside loops withoutt.Run— use subtests to isolate failures - ❌ Global mock state — define mocks locally within test scope
- ❌ Skipping race detection — always run
go test -racein CI