Senior
What testing tools, packages, and approaches are commonly used in Go, and how should they be applied in practice?
sobes.tech AI
Answer from AI
In Go, the standard testing package is most commonly used for testing, allowing you to write unit tests and integration tests.
Main tools and approaches:
testing— the basic package for writing tests, benchmarks, and examples.go test— command to run tests.- Table-driven tests — a convenient way to cover different scenarios with a single test.
- Mocking — libraries like
gomockortestify/mockare used to simulate dependencies. testify— a set of utilities for convenient assertions (assert,require) and mocks.- Code coverage — using
go test -coverto measure how much of the code is covered by tests.
Practical applications:
- Write tests immediately during function development.
- Use table-driven tests to verify different input data.
- Mock external dependencies to keep tests isolated.
- Write benchmarks for performance-critical sections.
- Run integration tests with real services or their emulators.
Example of a table-driven test:
func TestSum(t *testing.T) {
tests := []struct {
name string
a, b int
want int
}{
{"positive", 2, 3, 5},
{"zero", 0, 0, 0},
{"negative", -1, -1, -2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Sum(tt.a, tt.b)
if got != tt.want {
t.Errorf("Sum(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.want)
}
})
}
}