Testing in Go
Go has its testing tools built in. If you understand table-driven tests with subtests, the t.Helper and t.Cleanup helpers, testing handlers with httptest, small fakes instead of heavy mocks, integration tests with a real database, the race flag, benchmarks with b.Loop, fuzzing and testing time with synctest, you can answer most interview questions.
Author: bezzad
Contents
The problem: tests that prove nothing
Our order service has 80% test coverage. Still, this week:
- The coupon code “save10” did not work in lower case. The test only tried upper case.
- One test fails in CI every now and then. It has a two-second time.Sleep inside.
- The repository tests pass with a mock of the database, but the real query had an SQL error.
- A data race was found in production that no test saw.
In this lesson we see which testing tools Go has, and how to write tests that really find bugs.
The basics: the testing package
A test is a function in a file that ends with _test.go. Its name starts with Test, and it takes one parameter, a pointer to testing.T:
func TestDiscount(t *testing.T) {
got, err := Discount(1000, "SAVE10")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != 900 {
t.Errorf("got %d, want 900", got)
}
}
- The Errorf method records a failure, and the test goes on. The Fatalf method records a failure and stops the test right there.
- Write the failure message as “got X, want Y”, so you understand what happened without opening the code.
- The command go test ./… runs all tests of the project. The run flag runs only the tests whose names match a pattern.
Table-driven tests
Most Go tests are table-driven: a table of inputs and expected outputs, and one loop. This is what would have found our first bug:
func TestDiscount(t *testing.T) {
tests := []struct {
name string
price int
coupon string
want int
wantErr error
}{
{"no coupon", 1000, "", 1000, nil},
{"ten percent", 1000, "SAVE10", 900, nil},
{"lower case", 1000, "save10", 900, nil},
{"unknown", 1000, "HELLO", 0, ErrBadCoupon},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got, err := Discount(tt.price, tt.coupon)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("err = %v, want %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("got %d, want %d", got, tt.want)
}
})
}
}
- Each row is a subtest with its own name. If one fails, the others still run and are reported.
- Adding a case is one line. So edge cases are easy to add: zero, negative, empty string, lower case.
- The t.Parallel method runs subtests in parallel. Since Go 1.22 each loop turn has its own tt variable, so this is safe. In older versions a line tt := tt was needed.
- You can run one subtest alone, with the run flag and the test and subtest names.
Helpers: t.Helper and t.Cleanup
func newTestStore(t *testing.T) *Store {
t.Helper() // errors point to the caller's line
db := openTestDB(t)
t.Cleanup(func() { db.Close() }) // runs after the test
return &Store{db: db}
}
- The t.Helper method says this function is a helper. When something fails inside it, Go shows the line of the test that called it.
- The t.Cleanup method registers a function to run after the test (and all its subtests) ends. It is better than defer for closing resources, because it works from inside a helper too.
- The t.TempDir method makes a temporary folder that is removed after the test. Since Go 1.24 the t.Context method also gives a context that is cancelled just before the cleanups run.
Testing an HTTP handler
The net/http/httptest package gives a fake request and a response recorder. No real server or port is needed:
type fakeStore struct {
order Order
err error
}
func (f fakeStore) Order(id int64) (Order, error) {
return f.order, f.err
}
func TestGetOrder(t *testing.T) {
store := fakeStore{order: Order{ID: 42, Total: 900}}
h := &Handler{Store: store}
req := httptest.NewRequest("GET", "/orders/42", nil)
rec := httptest.NewRecorder()
h.GetOrder(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
if !strings.Contains(rec.Body.String(), `"total":900`) {
t.Errorf("body = %s", rec.Body)
}
}
- The handler depends on a small interface (here OrderStore, with one method). So a simple two-line fake is enough in the test.
- A simple fake beats a heavy mock. A mock that checks the order of calls breaks with every small internal change. A fake only imitates behavior.
- For an HTTP client, the httptest.NewServer function starts a real server on a local port. With it you can test the payment provider client.
Integration tests with a real database
Our third bug was this: a database mock does not run the SQL query, so it does not see an SQL error. For repositories, run tests against a real database:
- The testcontainers-go library starts a real Postgres container for the test and removes it after.
- These tests are slower. With testing.Short you can skip them in a quick run, or keep them apart with a build tag.
- Each test makes its own data, or runs inside a transaction that is rolled back at the end. Tests that share data start to depend on the run order.
The race flag
Our fourth bug was a data race. The race detector would have found it:
go test -race ./...
- The race detector reports every unsynchronized concurrent memory access where at least one access is a write.
- It only sees code that really runs. So you need a test that really runs several goroutines at once.
- It makes the program slower and uses more memory, so it is not turned on in production. But in CI it should always be on.
Testing time and goroutines: synctest
Our second bug was a time.Sleep in a test. A test that waits for real time is both slow and flaky: on a busy CI machine, two seconds is sometimes not enough.
Since Go 1.25 the testing/synctest package solves this. The synctest.Test function runs the test inside a “bubble” with a fake clock:
func TestReservationExpires(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
r := NewReservations(15 * time.Minute)
r.Reserve("order-42", "shoe")
time.Sleep(16 * time.Minute) // instant: fake clock
synctest.Wait() // wait until goroutines are idle
if r.Has("order-42") {
t.Error("reservation should expire")
}
})
}
- Inside the bubble, time moves forward only when all goroutines of the bubble are waiting. So a 16-minute Sleep ends at once.
- The synctest.Wait function waits until all goroutines of the bubble are blocked. So the result is always the same.
- Without synctest, the common way is to give time to the code as a dependency (for example a now function) and control it in the test.
Measuring speed with benchmarks
A benchmark measures the speed of a function. Since Go 1.24 its loop is written with b.Loop:
func BenchmarkDiscount(b *testing.B) {
for b.Loop() {
Discount(1000, "SAVE10")
}
}
- The go test command with the bench flag runs benchmarks. The benchmem flag also shows the number and size of allocations per run.
- The b.Loop method keeps setup work before the loop out of the timing, and stops the compiler from removing the call inside the loop.
- One run is not enough. Run the old and new code several times and compare them with the benchstat tool.
Fuzz tests
A fuzz test makes strange inputs by itself and looks for an input that breaks a rule:
func FuzzParseSKU(f *testing.F) {
f.Add("ab-123") // seed inputs
f.Add(" shoe ")
f.Fuzz(func(t *testing.T, s string) {
sku, err := ParseSKU(s)
if err != nil {
return
}
// Rule: parsing a parsed SKU gives the same SKU.
if again, _ := ParseSKU(sku); again != sku {
t.Errorf("not stable: %q -> %q", sku, again)
}
})
}
- The go test command with the fuzz flag starts the search. Without this flag, only the seed inputs run, so a normal CI run stays fast.
- When the fuzzer finds a bad input, it saves it in the testdata folder. From then on, this input is part of the normal tests.
- In a real run of this very example, the fuzzer found an invalid UTF-8 string within seconds. The ToUpper function replaced the invalid bytes with a three-byte character, so the SKU grew over the 20-byte limit and was rejected the second time. The fix was to reject invalid input at the start.
- Fuzzing gives the most value for parsers and any code that reads user input.
Common mistakes
| Mistake | Result | The right way |
|---|---|---|
| One copied test per case | Edge cases are missed. | A table-driven test with subtests |
| Using time.Sleep in a test | A slow and flaky test | The synctest package or a controllable clock |
| Only mocks for the database | Real SQL errors are not seen. | An integration test with a real database |
| Running CI without the race flag | Data races reach production. | go test -race in CI |
| A heavy mock that checks the order of calls | Breaks with every internal change. | A small interface and a simple fake |
| Data shared between tests | The result depends on the run order. | Each test’s own data, or a rolled-back transaction |
| Comparing speed from one run | The result is noise. | Several runs and benchstat |
| Aiming for a coverage number | Tests without real checks | Test behavior and edge cases |
Summary in seven lines
- Tests live in _test.go files and run with go test. Write failure messages as “got, want”.
- A table-driven test with t.Run makes one subtest per case and makes edge cases easy to add.
- Use t.Helper, t.Cleanup and t.TempDir for clean helpers.
- Test handlers with httptest and a small fake, and repositories with a real database.
- Keep the race flag on in CI, and write concurrent tests for concurrent code.
- Instead of time.Sleep, use synctest in Go 1.25 or a controllable clock.
- Measure speed with benchmarks and b.Loop, and test parsers with fuzzing.