testing package provides the tools we need to write unit tests and the go test command runs tests.
Basic Testing
Go has a built-in testing framework that makes it easy to write and run tests. Test files are named with a_test.go suffix and contain functions that begin with Test.
Simple Test Example
Here’s a simple function and its test:Test files typically live in the same package as the code they test. For example, code in
intutils.go would have tests in intutils_test.go.Test Function Requirements
A valid test function must:Table-Driven Tests
Writing tests can be repetitive, so it’s idiomatic to use a table-driven style where test inputs and expected outputs are listed in a table and a single loop walks over them and performs the test logic.Running Tests
Use thego test command to run tests:
Sample Output
Benchmarking
Benchmark tests measure the performance of your code. They follow a similar pattern to unit tests but use different naming and parameters.Writing Benchmarks
Benchmark functions:- Must begin with
Benchmark - Accept a
*testing.Bparameter - Run the code being benchmarked in a loop using
b.Loop()
Any setup code that’s required for the benchmark to run but should not be measured goes before the
b.Loop() loop. The benchmark runner will automatically execute the loop body many times to determine a reasonable estimate of the run-time of a single iteration.Running Benchmarks
Use the-bench flag to run benchmarks:
bench flag filters benchmark function names with a regexp. Use . to run all benchmarks.
Sample Benchmark Output
Understanding Benchmark Output
Understanding Benchmark Output
BenchmarkIntMin-8: Benchmark name with GOMAXPROCS value (8)1000000000: Number of iterations run0.3136 ns/op: Time per operation in nanoseconds
Benchmark Best Practices
Benchmark Best Practices
- Avoid setup code inside the benchmark loop
- Use
b.ResetTimer()if setup is necessary before timing - Run benchmarks multiple times to ensure consistency
- Use
-benchmemto include memory allocation statistics
Testing Methods
t.Error / t.Errorf
Report test failures but continue executing the test
t.Fatal / t.Fatalf
Report test failures and stop the test immediately
t.Run
Run subtests for table-driven tests or test grouping
t.Skip / t.Skipf
Skip the test with a message explaining why
Complete Example
Next Steps
Testing Package
Explore the full testing package documentation
Go Test Command
Learn about all go test command options