Golang Testing Standards
Priority: P0 (CRITICAL)
Guidelines
TDD & Table-Driven Tests
- Pattern: Use
Table-Driven Testsfor multi-input scenarios. Uset.Run()for each test case. - Workflow: Follow Red-Green-Refactor. Write a failing test case before implementing logic.
- Mocking: Use
InterfacesandDependency Injection. Avoid complex mocking frameworks; prefermanual mocksorGoMock. - Coverage: Aim for
> 80%line coverage. Rungo test -coverto audit. - Assertions: Use
testify/assertortestify/requirefor readable checks:assert.NoError(t, err). - Parallelism: Use
t.Parallel()for non-sequential tests to speed up CI. - Cleanup: Use
t.Cleanup()to reset state or release resources (DB/Files). - Subtests: Name each subtest case clearly (
"Valid input","Missing ID","Network timeout").
Golden Snippet
See Table-Driven Tests for full template.
Tools
- Stdlib:
testingpackage is usually enough. - Testify (
stretchr/testify): Assertions (assert,require) and Mocks. - Mockery: Auto-generate mocks for interfaces.
- GoMock: Another popular mocking framework.
Naming
- Test file:
*_test.go - Test function:
func TestName(t *testing.T) - Example function:
func ExampleName()
Anti-Patterns
- No Manual Mocks: Use
mockeryfor boilerplate-heavy mocks. - No Assert in Loop: Use
t.Runto isolate failures within table-driven loops. - No Global Mocks: Define mocks locally or within test scope to avoid state leakage.
References
- Table-Driven Tests
- Mocking Strategies