Go - Testing & Benchmarking

Beginner 10/10 Teacher 10/10 Architect 10/10

Unit Tests

// file: mathx_test.go
package mathx
import "testing"
func TestAdd(t *testing.T){
  if got := Add(2,3); got != 5 { t.Fatalf("want 5, got %d", got) }
}

Table-Driven

func TestAbs(t *testing.T){
  cases := []struct{ in, want int }{{-1,1},{0,0},{2,2}}
  for _, c := range cases {
    if got := Abs(c.in); got != c.want { t.Fatalf("%v", got) }
  }
}

Benchmarks

func BenchmarkAdd(b *testing.B){
  for i := 0; i < b.N; i++ { _ = Add(2,3) }
}

Commands

  • go test ./...
  • go test -bench .
  • go test -race to enable race detector