Testing Basics

View saved

Create a test file

Name tests *_test.go in the same package. Run them with go test.

// add.go
package mathx

func Add(a, b int) int { return a + b }

// add_test.go
package mathx

import "testing"

func TestAdd(t *testing.T) {
	got := Add(2, 3)
	if got != 5 {
		t.Fatalf("Add(2,3)=%d, want 5", got)
	}
}

Run tests

From the package directory:

go test
go test -v

Table-driven tests

Loop over cases to cover several inputs cleanly.

cases := []struct{ a, b, want int }{
	{1, 2, 3},
	{0, 0, 0},
}
for _, tc := range cases {
	if Add(tc.a, tc.b) != tc.want {
		t.Fatalf("%v", tc)
	}
}

Testing tips

  • Fail with t.Error or t.Fatal
  • Keep tests fast and deterministic
  • Export only what production code needs; test exported behavior
  • Add benchmarks later with Benchmark* functions

Comments

One comment per signed-in account. Comments are saved with this page’s URL.