Testing Go Code
Every developer has said the words "it works on my machine." Fewer have said the more honest version: "it worked when I last tried it, three changes ago, I think."
Without tests, that second sentence is the real state of most software. You change something, you poke at it, nothing visibly explodes, and you ship, with the quiet hope of a person who has just closed a suitcase that clearly shouldn't close.
Tests replace hope with evidence. And Go makes writing them pleasantly easy, because the testing tools are built into the language. No framework to install, no configuration file, no ceremony.
This article walks through the essentials: writing your first tests, the famous table-driven style, using fakes instead of real dependencies, measuring coverage, and building the habit of tests that you actually trust.
Your First Test
Go's rules are simple. Put tests in a file ending in _test.go, next to the code they test. Name each test function TestSomething, taking a *testing.T. That's it.
Suppose we have a small function:
// price.go
package shop
func ApplyDiscount(price int, percent int) int {
return price - (price * percent / 100)
}
And its test:
// price_test.go
package shop
import "testing"
func TestApplyDiscount(t *testing.T) {
got := ApplyDiscount(1000, 10)
want := 900
if got != want {
t.Errorf("ApplyDiscount(1000, 10) = %d, want %d", got, want)
}
}
Run everything with:
go test ./...
The ./... means "this directory and everything below it." You'll type it so often it becomes a reflex.
Two functions on t are worth distinguishing:
t.Errorfrecords a failure and continues running the test, so you can see multiple problems at once.t.Fatalfrecords a failure and stops the test immediately. Use it when continuing makes no sense, like when a setup step failed and the rest would just crash on a nil pointer.
A pleasant convention: write failure messages in the form "got X, want Y," and include the input. A failure message is a note to future you, who will be tired and annoyed. Make it kind.
Table-Driven Tests: The Go Signature Move
Our test checks one case. Real functions have many: zero percent, 100 percent, negative prices, rounding edges. Writing a separate test function for each is repetitive. Go's answer is the table-driven test: list your cases as data, then loop.
func TestApplyDiscount(t *testing.T) {
tests := []struct {
name string
price int
percent int
want int
}{
{"no discount", 1000, 0, 1000},
{"ten percent", 1000, 10, 900},
{"half price", 1000, 50, 500},
{"full discount", 1000, 100, 0},
{"rounds down", 999, 10, 900},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := ApplyDiscount(tc.price, tc.percent)
if got != tc.want {
t.Errorf("ApplyDiscount(%d, %d) = %d, want %d", tc.price, tc.percent, got, tc.want)
}
})
}
}
Think of it as a spreadsheet of expectations: each row is a scenario, and one small engine runs them all. The benefits are huge:
- Adding a case is one line. Found a bug? Add the failing input as a new row, fix the code, and the row stays forever as a guard.
- Each row is a named subtest via
t.Run. When one fails, the output says exactly which:--- FAIL: TestApplyDiscount/rounds_down. - You can run a single case from the command line:
go test -run 'TestApplyDiscount/half_price'.
Notice that row "rounds down" made us think about what the function should do with 999 and 10%. Table tests are secretly a design tool: writing the table forces you to enumerate the edge cases you'd otherwise forget.
Testing Errors in a Table
Add an expected-error column:
tests := []struct {
name string
input string
want int
wantErr error
}{
{"valid", "25", 25, nil},
{"negative", "-3", 0, ErrNegativeAge},
{"not a number", "abc", 0, ErrNotNumber},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := ParseAge(tc.input)
if !errors.Is(err, tc.wantErr) {
t.Fatalf("error = %v, want %v", err, tc.wantErr)
}
if got != tc.want {
t.Errorf("got %d, want %d", got, tc.want)
}
})
}
Use errors.Is here, matching the way you handle errors in real code, so wrapped errors still compare correctly.
Fakes, Stubs, and Mocks: Standing In for Dependencies
Business logic rarely lives alone. A service calls a repository, which calls a database. To test the service in isolation, we replace the real dependency with a stand-in. The vocabulary gets muddy, so here's a simple map:
- Stub: returns canned answers. "When asked for user 7, return this user."
- Fake: a lightweight working version. An in-memory map pretending to be a database.
- Mock: records how it was called, so you can assert "this method was invoked twice with these arguments."
Because Go interfaces are satisfied implicitly, creating any of these is easy. Suppose a service depends on:
type UserStore interface {
FindByEmail(ctx context.Context, email string) (*domain.User, error)
Create(ctx context.Context, u *domain.User) error
}
A hand-written fake:
type fakeUserStore struct {
users map[string]*domain.User
createErr error
createCalls int
}
func newFakeUserStore() *fakeUserStore {
return &fakeUserStore{users: map[string]*domain.User{}}
}
func (f *fakeUserStore) FindByEmail(_ context.Context, email string) (*domain.User, error) {
if u, ok := f.users[email]; ok {
return u, nil
}
return nil, domain.ErrNotFound
}
func (f *fakeUserStore) Create(_ context.Context, u *domain.User) error {
f.createCalls++
if f.createErr != nil {
return f.createErr
}
f.users[u.Email] = u
return nil
}
This one is a fake and a bit of a mock at once: it stores data, injects failures through createErr, and counts calls. For small interfaces, hand-written test doubles are more readable than any framework. You see exactly what they do, with no magic, no code generation, and no configuration language to learn.
Then the test:
func TestRegister(t *testing.T) {
t.Run("rejects duplicate email", func(t *testing.T) {
store := newFakeUserStore()
store.users["a@b.com"] = &domain.User{Email: "a@b.com"}
svc := NewUserService(store, fakeHasher{})
_, err := svc.Register(context.Background(), "a@b.com", "password123")
if !errors.Is(err, domain.ErrEmailTaken) {
t.Fatalf("got %v, want ErrEmailTaken", err)
}
if store.createCalls != 0 {
t.Errorf("Create should not be called for duplicates")
}
})
t.Run("surfaces storage failures", func(t *testing.T) {
store := newFakeUserStore()
store.createErr = errors.New("disk on fire")
svc := NewUserService(store, fakeHasher{})
_, err := svc.Register(context.Background(), "n**@b.com", "password123")
if err == nil {
t.Fatal("expected an error")
}
})
}
Notice we tested a sad path, the database failing, which is nearly impossible to trigger on demand with a real database. With a fake, it's one assignment. Testing how your code behaves when things go wrong is where fakes shine brightest.
If your interfaces grow large, tools like gomock or mockery can generate mocks. They're useful, but start by hand. Needing a code generator to test a three-method interface is a signal the interface may be too big.
Test the Behavior, Not the Implementation
A trap awaits eager testers: tests that mirror the code line for line. If your test asserts "the function calls repo.Find exactly once, then hasher.Hash exactly once, in that order," then every harmless refactor breaks it. You've nailed the furniture to the floor.
Better to assert outcomes: what was returned, what ended up stored, what error appeared. Ask "what would a user of this function care about?" and test that. Tests should fail when behavior breaks, not when someone renames a variable.
Helpers, Setup, and Cleanup
When several tests need the same setup, extract a helper, and mark it with t.Helper() so failures point at the calling line instead of inside the helper:
func newTestService(t *testing.T) (*UserService, *fakeUserStore) {
t.Helper()
store := newFakeUserStore()
return NewUserService(store, fakeHasher{}), store
}
For resources that need tearing down, use t.Cleanup:
func setupTempDir(t *testing.T) string {
t.Helper()
dir := t.TempDir() // automatically deleted after the test
return dir
}
t.TempDir() gives each test its own scratch folder and cleans it up for you. Small conveniences like this keep tests tidy and independent.
Controlling Time and Randomness
Tests that depend on the current time or random values are flaky in the worst way: they pass for months, then fail at midnight on the last day of the month. The cure, as in our service layer discussion, is to inject the source:
type Service struct {
now func() time.Time
}
// in the test
svc.now = func() time.Time { return time.Date(2026, 1, 15, 9, 0, 0, 0, time.UTC) }
Now "is this coupon expired?" has a deterministic answer. You've become the master of time, a power usually reserved for sci-fi villains.
Running Faster, Running Safer
A few flags you'll love:
go test ./... # run everything
go test -v ./... # verbose: show every test name
go test -run TestRegister # only tests matching a pattern
go test -count=1 ./... # bypass the result cache
go test -race ./... # detect data races
go test -cover ./... # show coverage percentage
The race detector (-race) deserves special praise. If your code uses goroutines, it watches for unsynchronized access to shared data, one of the nastiest bug categories, because races appear rarely and vanish when you look. Run -race in your CI pipeline. It's like hiring a very pedantic inspector who only complains about real problems.
Parallel tests. Mark independent tests with t.Parallel() to run them concurrently, and watch the suite shrink:
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
// ...
})
Only do this if the tests share no mutable state. In older Go versions, loops capture variables in a surprising way, so check which Go version you're on.
Coverage: A Flashlight, Not a Trophy
go test -coverprofile=cover.out ./...
go tool cover -html=cover.out
The second command opens a page that highlights tested lines in green and untested ones in red. That's genuinely useful for spotting forgotten branches.
But resist the cult of the percentage. 100% coverage means every line ran, not that every behavior was verified. A test with no assertions can "cover" code completely and prove nothing. Use coverage as a flashlight for finding dark corners, not as a scoreboard. A well-tested 80% beats a hollow 100%.
Unit Tests vs Integration Tests
Unit tests check one piece in isolation, using fakes. They're fast, which means you run them constantly. Integration tests check that real pieces work together: your repository against a real PostgreSQL, for example. They're slower and need infrastructure, but they catch the bugs fakes can't, like a typo in a SQL column name.
Keep them separate so the quick ones stay quick. A popular approach is a build tag:
//go:build integration
package repository_test
Run them on demand with go test -tags=integration ./.... Run unit tests on every save, integration tests before each commit or in CI.
Naming and Organizing
Name tests after behavior: TestRegister_DuplicateEmail beats TestRegister2. Use package foo_test (external test packages) when you want to test only the public API, and plain package foo when you need access to internals. Keep test data close, inside the test or in a testdata/ folder, which Go tooling deliberately ignores. Don't share mutable state between tests. Each test should set up its own world, so order never matters.
Common Mistakes
- Tests that depend on each other. If test B only passes after test A ran, you've built a house of dominoes. Each test sets up and tears down its own world.
- Flaky tests left alone. A test that sometimes fails teaches the team to ignore failures, which is worse than having no tests. Fix it or delete it.
- Testing the framework. You don't need to verify that GORM saves a row or that Gin returns JSON. Test your logic.
- Only happy paths. Empty input, huge input, missing records, dependency failures. Bugs live in the corners.
- Chasing coverage numbers. Assertions matter, not line counts.
- Slow unit tests. If your "unit" test touches the network or a real database, it's an integration test in disguise. Move it, or fake the dependency.
- Hard-to-read failure messages. expected true, got false is a riddle. Include inputs and expected values.
Quick Recap
Go's testing tools are built in. Files end in _test.go and functions start with Test. Table-driven tests with t.Run turn edge cases into one-line additions. Hand-written fakes beat frameworks for small interfaces, and make failure scenarios easy to trigger. Test behavior and outcomes, not the exact internal steps. Inject time and randomness to keep tests deterministic. Use -race often, -cover as a flashlight, and t.TempDir and t.Cleanup for tidy setup. Separate fast unit tests from slower integration tests.
Comments
No comments yet. Start the discussion.