Skip to content

Testing and benchmarking

The testing package provides unit tests and benchmarks. Write tests in *_test.go files. Benchmarks measure performance.

Test a function and benchmark it.

// main.go
package main
func Add(a, b int) int {
return a + b
}
// main_test.go
package 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)
}
}
Terminal window
PASS
BenchmarkAdd-8 1000000000 0.25 ns/op