Structs and methods in Go: definition, literals, and comparability; choosing value vs. pointer receivers; embedding and composition over inheritance; construction patterns like NewX and functional options; and JSON tags for clean data models.
Imagine we run a small shop, and support reports: "Articles with special characters generate broken URLs." The culprit is a NormalizeSlug function that turns titles into URL-friendly slugs — and it behaves differently for whitespace, umlauts, and empty strings. Functions with many input classes like this are exactly where bugs settle in.
The naive reaction is to copy a test function per suspicion: TestSlugSimple, TestSlugUmlaut, TestSlugEmpty ... After the tenth duplicate, nobody knows which cases are covered anymore. Go has an idiomatic answer to this that runs through the entire standard library: table-driven tests. The cases live as data in a table — a slice of anonymous structs — and a single test function loops over every row.
The Case Is Data, Not Code
In a table-driven test, every case is a row in a slice: name, input (in), and expected output (want). A new case costs one line, not a new func Test.... The table doubles as a checklist of requirements — in code review you see at a glance which edge cases someone actually thought of.
Here is the pattern — with subtests via t.Run, so every case gets a name:
// slug/slug_test.go
package slug
import (
"strings"
"testing"
)
// NormalizeSlug turns a title into a URL-friendly slug.
func NormalizeSlug(title string) string {
s := strings.ToLower(strings.TrimSpace(title))
s = strings.ReplaceAll(s, " ", "-")
return strings.Trim(s, "-")
}
func TestNormalizeSlug(t *testing.T) {
tests := []struct {
name string
in string
want string
}{
{name: "simple title", in: "Go course", want: "go-course"},
{name: "surrounding spaces", in: " Panic ", want: "panic"},
{name: "multiple words", in: "goroutines and channels", want: "goroutines-and-channels"},
{name: "empty string", in: "", want: ""},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := NormalizeSlug(tc.in)
if got != tc.want {
t.Errorf("NormalizeSlug(%q) = %q, want %q", tc.in, got, tc.want)
}
})
}
}
// Terminal: go test ./slug
// → ok slug 0.012s
The t.Run in the loop is not decoration. Each table row becomes a named subtest with three benefits: failures show up with the case name, -run lets you replay a single case, and you can debug a failing case in isolation without silencing the rest of the table.
// Terminal: replay one regression in isolation
//
// go test -run 'TestNormalizeSlug/multiple' -v ./slug
//
// → === RUN TestNormalizeSlug
// → === RUN TestNormalizeSlug/multiple_words
// → --- PASS: TestNormalizeSlug (0.00s)
// → --- PASS: TestNormalizeSlug/multiple_words (0.00s)
// → PASS
Subtest names come from the name field — spaces automatically become underscores. Name your cases clearly ("empty string" instead of "case 3") and you get failure messages you understand without opening the editor.
For assertions one rule of thumb applies: t.Errorf reports the failure and keeps the test running, t.Fatalf aborts immediately. Fatalf is right when the following code could not meaningfully use the checked value anyway — for instance because it gets dereferenced next. Inside a subtest, the abort only affects that one case.
⚠ Common mistake: Calling
t.Fatalfdirectly inside the loop over the table — withoutt.Run. Fatal then ends the entire test function at the first failing case: you fix one case, rerun, and only now the next failure appears. Witht.Runplust.Errorfyou see every failing case in a single run instead of discovering them one by one across five CI runs.
Check: Inside a subtest started with t.Run, t.Fatalf is called. What happens?
Answer: Only this subtest aborts; the remaining cases in the table keep running
Every t.Run block runs in its own test context: Fatal ends only the current subtest, then Go continues with the next case. That is exactly why subtests show you all failing cases in one run instead of revealing them one at a time.
Takeaways:
func Test....t.Run turns every case into a named subtest — failure messages become self-explanatory and -run filters precisely.t.Errorf collects, t.Fatalf aborts: use Fatal only when the remaining code depends on the checked value.A test that starts an HTTP server, writes a file, or opens a database connection has one duty: leave everything as it was. Otherwise a leaking file handle trips up the next test, and hunting down the cause takes longer than writing the test did.
Go ships three tools that together cover almost any test infrastructure: t.TempDir() for throwaway directories, t.Cleanup for teardown logic, and TestMain for setup that affects the whole package. Add t.Parallel, and Go runs the waiting I/O tests of a suite with overlap — a large suite suddenly finishes in half the time.
Bind Lifetime to the Test, Not the Function
t.Cleanup(f) registers a function that fires only when the test finishes — in reverse registration order (LIFO), just like defer. The difference from defer is the anchor point: defer in a helper fires as soon as the helper returns. t.Cleanup fires when the test is done. For resources a helper hands to the test, it is the only correct mechanism.
Here is a helper that starts a fake API server — including t.Helper(), so failure messages point at the line in the test instead of inside the helper:
// config/config_test.go
package config
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
// newAPIServer starts a test server that says ok for the right token.
func newAPIServer(t *testing.T, token string) *httptest.Server {
t.Helper() // failures report the test line, not the helper line
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+token {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Write([]byte(`{"status":"ok"}`))
}))
t.Cleanup(srv.Close) // fires when the test is done
return srv
}
func TestFetchStatus(t *testing.T) {
t.Parallel() // may run alongside other parallel tests
srv := newAPIServer(t, "secret")
path := filepath.Join(t.TempDir(), "status.json") // directory is removed automatically
if err := fetchToFile(srv.URL, "secret", path); err != nil {
t.Fatalf("fetchToFile: %v", err)
}
if _, err := os.Stat(path); err != nil {
t.Fatalf("file missing: %v", err)
}
}
// Terminal: go test ./config
// → ok config 0.021s
// Terminal: go test -v ./config
// → === RUN TestFetchStatus
// → --- PASS: TestFetchStatus (0.02s)
// → PASS
//
// Terminal: run all parallel tests of a package together
// → go test -parallel 8 ./...
Sometimes you need state that must exist before the first test: a test database with a schema, an expensive binary, or environment variables. For that there is TestMain(m *testing.M) — it replaces the main function of the test binary. The flow is always the same: setup, m.Run() (runs all tests and returns their exit code), teardown, os.Exit(code).
// store/main_test.go
package store
import (
"fmt"
"os"
"testing"
)
var testDB *DB
func TestMain(m *testing.M) {
var err error
testDB, err = open("postgres://localhost/shop_test")
if err != nil {
fmt.Println("setup failed:", err)
os.Exit(1)
}
code := m.Run() // runs ALL tests and returns the exit code
testDB.Close() // global teardown
os.Exit(code) // forward the exit code to CI
}
// Terminal: go test ./store
// → ok store 2.418s
// Terminal: go test -v ./store
// → === RUN TestOrderInsert
// → --- PASS: TestOrderInsert (0.03s)
// → PASS
//
// Without os.Exit(code) the test binary ends with exit code 0 —
// the CI stays green even when m.Run() returned FAIL.
⚠ Common mistake:
defer srv.Close()inside a helper function that returns the server to the test. Thedeferfires when the helper returns — before the test has even started — and the server is already closed. Helpers that hand out resources must uset.Cleanup;deferis only correct inside the test function itself, where the scopes coincide.
Check: What happens if TestMain discards the return value of m.Run() and never calls os.Exit(code)?
Answer: The test binary ends with exit code 0 even when tests fail — the CI stays green
m.Run() executes the tests and returns their exit code — but it does not terminate the process. Without os.Exit(code), TestMain returns normally, the binary exits 0, and failed tests look successful in the pipeline. The classic outcome: the test run was red, the deploy went ahead anyway.
Takeaways:
t.TempDir() and t.Cleanup clean up reliably — bound to the test, not to the helper function.t.Helper() makes failure messages point at the test line instead of the helper.t.Parallel() lets waiting I/O tests run with overlap; the suite gets faster, not slower.m.Run() in TestMain, always call os.Exit(code) — otherwise the CI stays green while tests fail.An order service is supposed to trigger a payment at a payment provider. If we call the real API in tests, one of three things happens: it costs money, it is slow, or it flakes the moment the provider has maintenance. None of these properties belong in a unit test.
The solution is not a mocking library but a language feature: interfaces. An interface defines the seam — the place where our code consumes a dependency purely through its behavior. In production the real Stripe adapter sits behind it; in a test it is a small fake that returns a transaction ID and remembers what it was called with.
The Interface Belongs to the Consumer
In Go, the consumer defines the interface, not the producer. The order service declares what it needs ("something that can Charge"), and the concrete payment implementation satisfies that requirement automatically — Go has no implements. This implicit satisfaction is exactly what makes interfaces the perfect test seam: the fake is just a type in the test package, and the production side never knows it exists.
The production code — the interface lives with the consumer, the field is the swap point:
// checkout/checkout.go
package checkout
import "context"
// PaymentGateway is everything the service needs for payments.
type PaymentGateway interface {
Charge(ctx context.Context, amountCents int) (txID string, err error)
}
type Order struct {
ID string
AmountCents int
}
type Service struct {
gw PaymentGateway // the fake gets plugged in here during tests
}
func (s *Service) PlaceOrder(ctx context.Context, o Order) (string, error) {
return s.gw.Charge(ctx, o.AmountCents)
}
// In production, the real adapter gets plugged in here:
// svc := &Service{gw: newStripeClient(apiKey)}
// Call: svc.PlaceOrder(ctx, Order{ID: "A-42", AmountCents: 4999})
// → txID = "ch_3Ox2...", err = nil
The fake in the test — one struct, three lines of logic:
// checkout/checkout_test.go
package checkout
import (
"context"
"testing"
)
type fakeGateway struct {
charged []int
}
func (f *fakeGateway) Charge(_ context.Context, amountCents int) (string, error) {
f.charged = append(f.charged, amountCents)
return "tx_fake_001", nil
}
func TestPlaceOrderChargesExactlyOnce(t *testing.T) {
gw := &fakeGateway{}
svc := &Service{gw: gw}
txID, err := svc.PlaceOrder(context.Background(), Order{ID: "A-42", AmountCents: 4999})
if err != nil {
t.Fatalf("PlaceOrder: %v", err)
}
if txID != "tx_fake_001" {
t.Errorf("txID = %q, want tx_fake_001", txID)
}
if len(gw.charged) != 1 || gw.charged[0] != 4999 {
t.Errorf("Charge was called with %v, want exactly once with 4999", gw.charged)
}
}
// Terminal: go test ./checkout
// → ok checkout 0.009s
// Terminal: go test -v ./checkout
// → === RUN TestPlaceOrderChargesExactlyOnce
// → --- PASS: TestPlaceOrderChargesExactlyOnce (0.00s)
// → PASS
httptest.NewServerNot everything hides behind an interface of our own — sometimes we test code that talks through an http.Client directly, for example an SDK-style client for a shipping API. No real endpoint needed here either: httptest.NewServer starts a real HTTP server on 127.0.0.1 with responses under our control. The code under test cannot tell it is talking to our fake.
// shipping/shipping_test.go
package shipping
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestClientReturnsErrorOn500(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer srv.Close() // inside the test itself, defer is correct
if err := FetchRates(srv.Client(), srv.URL); err == nil {
t.Fatal("expected an error on HTTP 500, got nil")
}
// → --- PASS: TestClientReturnsErrorOn500 (0.00s)
}
The rule for choosing is simple: a fake replaces a dependency behind our own interface when we test our behavior. An httptest server simulates a real endpoint when we test HTTP behavior itself — timeouts, status codes, retries. Together they cover almost every situation where other ecosystems reach for heavyweight mocking frameworks.
⚠ Common mistake: Declaring the interface next to the big implementation — say a
StripeClientwith twelve methods, just "to be able to mock it". The fake then has to implement all twelve methods even though the test only needsCharge. In Go, define the interface where it is consumed and keep it so small that a fake is three lines long.
Check: Why is a hand-written fake enough in tests, without a mocking framework generating method implementations?
Answer: Because interfaces are satisfied implicitly: any type with the right methods fits, without implements
Go has no explicit implements: any type carrying the interface's method signatures satisfies it automatically. A fake is therefore just a small struct with those methods — no framework, no code generation, no registration required.
Takeaways:
httptest.NewServer provides a real HTTP counterpart for testing HTTP clients — including status codes and timeouts.Two claims about the same code: "String concatenation with += in a loop is way too slow, use strings.Builder!" — "Nonsense, the compiler optimizes that by now." Both sides cite blog posts from 2019 and other people's measurements. In Go this discussion ends after two minutes, because the testing package ships benchmarks: a function with the signature BenchmarkXxx(b *testing.B), run with go test -bench, measures your own code on your own machine.
The pattern is always the same: the code under measurement runs in a loop over b.N iterations. The framework sets b.N itself — it raises the iteration count until the measurement is stable. So you never dictate how often is measured.
b.N Is Calibration, Not a Preset
The framework starts with a small b.N, measures, and keeps increasing until the total time is reliable. That is why the loop must run over b.N — a fixed number would skew the measurement. b.ResetTimer() drops the time spent on expensive setup before the loop, and b.ReportAllocs() (or the flag -benchmem) shows memory allocations — often the actual bottleneck.
Here is the comparison of the two disputed variants — with a package-level sink variable so the compiler cannot optimize the result away:
// render/render_test.go
package render
import (
"strings"
"testing"
)
// sink prevents the compiler from eliminating the computation as unused.
var sink string
func BenchmarkConcatPlus(b *testing.B) {
parts := []string{"<html>", "<body>", "<main>", "</main>", "</body>", "</html>"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
var s string
for _, p := range parts {
s += p
}
sink = s
}
}
func BenchmarkBuilder(b *testing.B) {
parts := []string{"<html>", "<body>", "<main>", "</main>", "</body>", "</html>"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
var sb strings.Builder
for _, p := range parts {
sb.WriteString(p)
}
sink = sb.String()
}
}
// Terminal: go test -bench=Builder ./render
// → BenchmarkBuilder-8 11584226 103.7 ns/op 56 B/op 1 allocs/op
// Terminal: go test -bench=. -benchmem ./render
// → BenchmarkConcatPlus-8 2062662 583.2 ns/op 216 B/op 8 allocs/op
// → BenchmarkBuilder-8 11584226 103.7 ns/op 56 B/op 1 allocs/op
//
// Reading: 583 vs 104 nanoseconds per operation — the Builder is
// roughly 5.6x faster here and causes 8x fewer allocations.
The numbers speak immediately: ns/op is the time per iteration, B/op the memory allocated per iteration, allocs/op the number of heap allocations. For a request handler that runs ten thousand times per second, that last column decides CPU load and garbage collector pressure.
A benchmark tells you that something is slow — but not why. For that, go test records a CPU profile out of the box. With -cpuprofile, the benchmark runs log which functions the time is spent in; go tool pprof reads the profile and sorts the hottest functions to the top.
// Terminal: record a profile and analyze it
//
// go test -bench=. -cpuprofile=cpu.out ./render
// go tool pprof -top cpu.out
//
// → Showing nodes accounting for 890ms, 89.00% of 1000ms total
// → flat flat% sum% cum cum% Function
// → 520ms 52.00% 52.00% 520ms 52.00% render.ConcatPlus
// → 180ms 18.00% 70.00% 310ms 31.00% runtime.growslice
The flat column shows time in the function itself, cum includes everything it calls. The runtime.growslice line is the profiler's tip: every += on a string allocates a new, ever-larger buffer — exactly the earlier suspicion, now backed by numbers. To go deeper, run go tool pprof cpu.out interactively (top, list FuncName) and see the time per source line.
⚠ Common mistake: Not using the result of the measured computation. The Go compiler removes unused calculations ruthlessly — if you never assign the built string, you are benchmarking an empty loop and get gorgeous, meaningless nanoseconds. Always assign to a package-level
sinkvariable or validate the result.
Check: What does the allocs/op column in benchmark output mean?
Answer: Heap allocations per iteration — a proxy for garbage collector pressure
allocs/op counts heap allocations per operation, and B/op the bytes allocated. Together they often explain why an operation is slow: every allocation means work for the garbage collector — and that work is paid by the whole application.
Takeaways:
testing package: BenchmarkXxx(b *testing.B), and the loop always runs over b.N.-benchmem (and B/op, allocs/op) explains slow code often better than raw ns/op.sink variable — otherwise the compiler optimizes the work away.go test -cpuprofile plus go tool pprof -top shows which functions the time actually goes to.Tests check the inputs we thought of. The failures that wake production systems at night almost always come from one of two families: inputs nobody thought of — a parser that panics on "12x" or an emoji string — and concurrency bugs that only strike when two goroutines touch the same field in the wrong millisecond. Go has built-in answers for both, since version 1.18 and 1.1 respectively: fuzzing and the race detector.
Let us start with fuzzing. A fuzz test looks like a table-driven test, except the framework fills the table: Go generates inputs systematically — guided by code coverage, not purely random — and calls our function with them. Our job is not to specify the expected output but to check a property (invariant) that must hold for every input: no panics, no negative results, roundtrips preserved.
Fuzzing Checks Properties, Not Expected Values
A unit test asks: what comes out for this input? A fuzz test asks: what must never happen for any input? Concretely: ParseDuration may return an error, but it must never panic and never return a negative result. If a generated input violates the invariant, the run stops and writes the culprit as a file into the testdata directory — from then on it is a permanent regression case in plain go test.
// duration/duration_test.go
package duration
import "testing"
// ParseDuration accepts formats like "90s" or "1h30m" — and never panics.
func FuzzParseDuration(f *testing.F) {
// seed corpus: typical formats, edge cases, and past crashes
f.Add("90s")
f.Add("1h30m")
f.Add("")
f.Add("12x")
f.Fuzz(func(t *testing.T, input string) {
d, err := ParseDuration(input)
if err != nil {
return // errors are explicitly allowed — panics are not
}
if d < 0 {
t.Errorf("ParseDuration(%q) = %v — negative is never allowed", input, d)
}
})
}
// Terminal: go test ./duration — without -fuzz only the seed cases run
// → ok duration 0.018s
// Terminal: go test -fuzz=. -fuzztime=10s ./duration
// → fuzz: elapsed: 2s, gathering baseline coverage: 0/192 completed
// → fuzz: elapsed: 5s, execs: 210432 (42086/sec), new interesting: 9 (total 12)
// → ---
// → FAIL: FuzzParseDuration
// → Failing input written to testdata/fuzz/FuzzParseDuration/6e5f8c4b
// → from now on, go test replays this file on every run
Two things make this tool so practical: the seeds from f.Add double as documentation of valid formats, and a discovered crash produces a file that regular go test automatically picks up as a case. The bug is therefore locked down forever from the moment it is found.
go test -race SeesNow for the second failure family. A counter incremented by four goroutines looks harmless — and without -race it usually even passes, because the overlapping accesses only collide sometimes. That is precisely what makes data races so dangerous: they are not deterministic and typically surface under real production load.
// counter/counter_test.go — version with unprotected n++
package counter
import (
"sync"
"testing"
)
func TestCounterParallel(t *testing.T) {
var n int
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 1000; j++ {
n++ // data race: four goroutines write without synchronization
}
}()
}
wg.Wait()
// Without synchronization the result fluctuates from run to run:
// → n = 3742, 3891, 4000 — updates are lost while accesses overlap
if n != 4000 {
t.Errorf("n = %d, want 4000 — lost updates", n)
}
}
// Terminal: go test -race ./counter
// → ==================
// → WARNING: DATA RACE
// → Read at 0x00c000014a09 by goroutine 8:
// → counter.TestCounterParallel.func1()
// → counter/counter_test.go:16 +0x3a
// → Previous write at 0x00c000014a09 by goroutine 7:
// → counter.TestCounterParallel.func1()
// → counter/counter_test.go:16 +0x50
// → FAIL
The detector does not just report the conflict — it shows both accesses with file, line, and goroutine. The repair is standard material from Module 7: a sync.Mutex around the critical section or, for simple counters, sync/atomic with atomic.AddInt64. The test above stays unchanged and verifies the fix: with synchronization, 4000 comes out reliably.
⚠ Common mistake: Running
go testin CI without-race. The race detector is not a static check — it instruments the build and runs at runtime, so it only sees accesses that actually overlap during that run. A race that slips through a normal run stays invisible. For concurrent code,go test -race ./...should be the default in every pipeline — the 2 to 5 times longer runtime is the price for deterministic failures instead of nightly mysteries.
Check: Why does the race detector find some data races only under load in CI — and some never?
Answer: Because it observes at runtime: it only sees accesses that actually overlap in that run
The detector is a runtime tool: it instruments every memory access and reports overlaps that actually happen during the test run. Whether two goroutines collide in time is decided by the scheduler — which is why you need parallel tests, real load, and the -race flag everywhere, not just on your laptop.
With that, the toolbox is complete — the one that makes Go code not just work but prove it works: tables make coverage cheap, helpers keep tests clean, interfaces make dependencies swappable, benchmarks make performance discussable, and fuzzing plus the race detector hunt the failures unit tests are blind to. Adopt these five into your workflow — tables instead of copy-paste, -race in CI, -benchmem for performance questions — and your modules stay stable when production load arrives.
Takeaways:
t.Run makes every case individually visible and addressable.t.TempDir, t.Cleanup, and TestMain with os.Exit(m.Run()) keep tests isolated, fast, and self-cleaning.httptest.NewServer replace real APIs.go test -bench with -benchmem and a CPU profile replace gut feeling with numbers — assign results to a sink variable.go test -race finds concurrency bugs that only appear under load — both belong in CI.Course navigation: ← Module 8 · All 20 modules · Module 10 →