Testing and Benchmarking in Go
Go has a built-in testing framework provided by thetesting package and the go test command. This makes writing tests a natural part of the development workflow, not an external dependency.
Writing Tests
Test files reside in the same package as the code they test, but with a_test.go suffix. For example, math.go would be tested by math_test.go.
Test Functions
A test function must start withTest and take a single argument t *testing.T.
Table-Driven Tests
Go developers prefer “table-driven tests” to easily cover multiple test cases without repeating code.Subtests (t.Run)
The t.Run method allows you to define subtests. This is useful for hierarchical test reporting and running specific subtests via the -run flag.
Benchmarking
Go also has built-in support for benchmarking code to measure performance. Benchmark functions start withBenchmark and take b *testing.B.
go test -bench=..
Examples
Example functions serve two purposes: they act as documentation (appearing in Godoc) and as verified tests. They start withExample and use // Output: comments to verify results.
Fuzzing
Go 1.18 introduced native support for fuzzing, which generates random inputs to find edge cases and bugs.Test Coverage
You can check code coverage with the-cover flag.
Summary
go test: The standard command to run tests.TestXxx: Unit tests.- Table-Driven Tests: Idiomatic way to structure tests.
BenchmarkXxx: Performance tests.ExampleXxx: Documentation that is also tested.- Fuzzing: Automated random testing to find edge cases.