Testing and benchmarking
Context
Section titled “Context”The testing package provides unit tests and benchmarks. Write tests in *_test.go files. Benchmarks measure performance.
Example
Section titled “Example”Test a function and benchmark it.
Code example
Section titled “Code example”// main.gopackage main
func Add(a, b int) int { return a + b}// main_test.gopackage main
import "testing"
func TestAdd(t *testing.T) { if Add(2, 3) != 5 { t.Error("Add(2,3) should be 5") }}
func BenchmarkAdd(b *testing.B) { for i := 0; i < b.N; i++ { Add(1, 2) }}Output (run go test -bench=.)
Section titled “Output (run go test -bench=.)”PASSBenchmarkAdd-8 1000000000 0.25 ns/op