Columns › 2. Writing a service › Part 8
Testing in Go: Table-Driven Tests, httptest and Integration Tests
測試:表格驅動、httptest、整合測試
Test every layer of the order service: table-driven tests for business-rule edge cases, httptest to verify handlers without a running server, and build-tagged integration tests against a real database that prove transactions and oversell protection actually work.
In this article
In the previous article, “database/sql, Transactions and Connection Pools in Go”, we connected the order service to a database and used transactions and conditional updates to prevent overselling. This article adds tests to every layer we have written so far, turning "this should be right" into facts that are checked automatically on every change.
What this article solves
So far, the way we have confirmed the program is correct is by firing a few requests with curl and eyeballing the responses. This has three problems: it is slow, so it doesn't get done often; it only checks the cases you happen to think of, so edge cases are easily skipped; and it cannot protect you during refactoring: change one thing and nobody knows whether something else broke.
Go's testing support is built straight into the toolchain: no extra test framework is needed, and go test plus the standard library's testing and net/http/httptest cover the vast majority of needs. Following the layers of the order service, this article writes the matching tests layer by layer:
- Table-driven tests check pure functions such as the total calculation, listing every edge case systematically.
- Hand-written test doubles replace dependencies, so only one layer's logic is tested.
- httptest tests the handler's routing, status codes and response content without starting a server.
- Integration tests connect to a real database to verify that transactions roll back and that concurrency does not oversell.
- Finally, the habits that keep tests fast, stable and repeatable.
Before starting, let's be clear about what each kind of test is for:
Figure: The lower the test, the faster and more stable it is, and the more of them you should have; the higher, the closer to reality, but the fewer there should be.
This "pyramid" is not a hard rule but a cost trade-off: unit tests finish in milliseconds and pinpoint the problem when they fail; integration tests need a database, run slowly, and when they fail it is harder to tell whether the code or the environment is at fault. A good strategy verifies most logic at the bottom and uses the upper levels only to verify that "the parts are still correct once connected". “Layered Architecture and Dependency Injection in Go” split the program into small interfaces and injectable dependencies precisely to make the bottom-level tests easy to write.
Step 1: The basic rules of go test
Go tests follow a few simple conventions:
- Test file names end in
_test.go; they are compiled only bygo testand never end up in the production binary. - Test function names start with
Test, with the signaturefunc TestXxx(t *testing.T). - A test file can be in the same package as the code under test (
package order) and access unexported identifiers, or it can use an external test package (package order_test) and use only the public API, testing from a user's point of view. Both can coexist in the same directory.
The most commonly used methods on *testing.T:
| Method | Effect | When to use |
|---|---|---|
t.Errorf | Records a failure and keeps going | Checking several independent fields, so you see every error at once |
t.Fatalf | Records a failure and ends this test immediately | Later checks are pointless, e.g. no need to compare content if decoding failed |
t.Run | Creates a subtest | Each case in a table-driven test |
t.Parallel | Marks the test as able to run alongside other parallel tests | Tests that share no mutable state |
t.Helper | Marks the function as a helper | The line number in failure messages points at the line that called the helper |
t.Cleanup | Registers a cleanup function to run when the test ends | Closing servers and database connections, deleting temporary data |
t.Context | Gets a test-specific context (since Go 1.24) | Cancelled automatically before the test ends; pass it to functions that need a context |
t.Skip | Skips this test | When a required external environment is missing |
t.Fatalf has an important limitation: it may only be called from the goroutine running the test function. Called from a goroutine you started yourself, it only ends that goroutine and the test itself does not stop. When you need to report an error from a goroutine, send it back to the main goroutine over a channel and check it there; the concurrency test in Step 5 does exactly this.
Common commands:
go test ./... # run the tests of every package in the module
go test ./internal/order -run TestTotal -v # run only tests matching the name, with verbose output
go test ./internal/order -run 'TestTotal/discount' # run only one subtest
go test -race -count=1 ./... # enable the data race detector and bypass the test cache
go test -shuffle=on ./... # shuffle test order to find tests that depend on each other
go test -cover ./... # show coverage
go test -tags=integration ./... # include the integration testsgo test caches passing results: when neither the code nor the tests have changed, a second run just shows (cached). That is handy in everyday development, but if a test depends on external state (such as database contents), force a re-run with -count=1.
Step 2: Table-driven tests
Calculating an order total is a typical pure function: items and a discount go in, a total or an error comes out, with no side effects. This kind of function is ideal for a table-driven test: each case is written as a row in a table, and the same logic verifies them one by one. First, the function under test:
// Snippet: internal/order/pricing.go
package order
import (
"errors"
"fmt"
)
var (
ErrNoItems = errors.New("order has no items")
ErrBadQuantity = errors.New("quantity must be positive")
ErrBadDiscount = errors.New("discount must be between 0 and 100")
)
type Item struct {
ProductID int64
Qty int
Price int64 // unit: cents
}
// Total calculates the order total; discountPct is an integer percentage, and the discounted amount is rounded down to the cent.
func Total(items []Item, discountPct int) (int64, error) {
if len(items) == 0 {
return 0, ErrNoItems
}
if discountPct < 0 || discountPct > 100 {
return 0, fmt.Errorf("%w: got %d", ErrBadDiscount, discountPct)
}
var sum int64
for _, it := range items {
if it.Qty <= 0 {
return 0, fmt.Errorf("product %d: %w", it.ProductID, ErrBadQuantity)
}
sum += it.Price * int64(it.Qty)
}
return sum * int64(100-discountPct) / 100, nil
}It has several rules that need verifying: no items must return an error, the quantity must be positive, the discount must be between 0 and 100, and the discounted amount is rounded down to the cent. The matching test:
// internal/order/pricing_test.go
package order
import (
"errors"
"testing"
)
func TestTotal(t *testing.T) {
tests := []struct {
name string
items []Item
discount int
want int64
wantErr error
}{
{
name: "single item",
items: []Item{{ProductID: 1, Qty: 2, Price: 150}},
want: 300,
},
{
name: "discount rounds down",
items: []Item{{ProductID: 1, Qty: 1, Price: 999}},
discount: 15,
want: 849, // 999 * 0.85 = 849.15, rounded down to 849
},
{
name: "full discount",
items: []Item{{ProductID: 1, Qty: 3, Price: 100}},
discount: 100,
want: 0,
},
{
name: "no items",
items: nil,
wantErr: ErrNoItems,
},
{
name: "zero quantity",
items: []Item{{ProductID: 1, Qty: 0, Price: 100}},
wantErr: ErrBadQuantity,
},
{
name: "discount over 100",
items: []Item{{ProductID: 1, Qty: 1, Price: 100}},
discount: 101,
wantErr: ErrBadDiscount,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
got, err := Total(tc.items, tc.discount)
if !errors.Is(err, tc.wantErr) {
t.Fatalf("Total() error = %v, want %v", err, tc.wantErr)
}
if got != tc.want {
t.Errorf("Total() = %d, want %d", got, tc.want)
}
})
}
}Why use a table
- Adding a case costs almost nothing. When you discover a new edge case, you just add a row to the table instead of copying the whole test logic. This encourages you to list every edge: zero, negative numbers, exactly at the limit, just over the limit.
- Cases are readable at a glance. Each row says "what the input is, what is expected", so the table itself is the function's specification.
- Subtests have names.
t.Run(tc.name, ...)makes each case an independent subtest; failure messages showTestTotal/discount_rounds_down, and you can re-run just that one with-run.
A few details of the technique
How errors are compared. The table's wantErr is a sentinel error, compared with errors.Is(err, tc.wantErr). This neatly covers two situations at once: when success is expected, wantErr is nil and errors.Is(nil, nil) is true, whereas if an error is actually returned, errors.Is(err, nil) is false and the test fails. When a specific error is expected, errors.Is still recognises it even if Total wrapped it with extra context using %w. This is the practical payoff of using sentinel errors and %w, as stressed in “Error Handling in Go: Wrapping, Sentinels and Custom Types”: tests don't have to compare error message strings, so rewording a message doesn't break them.
Running in parallel. Calling t.Parallel() in a subtest makes the cases run at the same time. Since Go 1.22 each loop iteration gets a fresh variable, so the old tc := tc line is no longer needed; but make sure the cases really share no mutable state.
Failure messages should explain themselves. A good failure message has the form "what was called, what was got, what was wanted", e.g. Total() = 850, want 849. One look at that line tells you where the problem is, without re-running with debug prints.
Comparing complex structures. In the example, comparing integers with != is enough. When comparing structs, you can also use == directly as long as every field is comparable; for structs containing slices or maps, use reflect.DeepEqual or the widely used github.com/google/go-cmp/cmp, which prints the difference between the two and makes failures easier to understand.
Tip: Comments on expected values in the table (such as
999 * 0.85 = 849.15, rounded down to 849) are valuable. They record "why the expected value is this number", so when someone later doubts the rule, they don't have to derive it all over again.
Step 3: Isolate dependencies with test doubles
The service depends on the repository, and the handler depends on the service. To test just one layer, you have to replace its dependencies with test doubles. In Go, doubles are usually hand-written, because interfaces are already defined by the consumer and kept small:
| Kind of double | Behaviour | Example |
|---|---|---|
| stub | Returns fixed results prepared in advance | Always returns a particular order or error |
| fake | Has a simplified but working implementation | Simulates storage with a map; can save and load |
| spy | Records how it was called, for checking afterwards | Remembers the order Create received |
| mock | Has expected calls set up in advance; fails on a mismatch | Usually generated by a tool |
The previous article already showed testing the service with a stub: the double remembers the order saved into it, and together with a clock function that returns a fixed time, the total, status and creation time can be verified precisely. The handler test in this article uses a fake instead: it simulates data with a map and can be set to always return a particular error, to simulate a database failure.
Hand-written doubles and mock generators each have trade-offs. Hand-written doubles are easy to read, and tests read like descriptions of behaviour; mock tools suit cases where you need to verify precisely "how many times a method was called and with what arguments", but tests tend to become tightly coupled to implementation details, so a refactor that doesn't change behaviour still forces big changes to the tests. The general advice is to verify outcomes rather than the sequence of calls: rather than checking that "the repository's Create was called once", check that "the order you Get afterwards is correct".
Two more tools commonly used when writing doubles and helpers:
t.Helper(): called at the start of a helper function, it makes the line number on failure point at the line in the test that called the helper, rather than inside the helper; otherwise every failure shows the same line number inside the same helper, and it is hard to tell which case failed.t.Cleanup(f): registers a cleanup action that runs, in last-in-first-out order, after the test (including all its subtests) finishes. Its advantage overdeferis that it can be written inside a helper: the helper creates a resource and registers its cleanup in the same breath, and the caller doesn't have to deal with it at all.
Step 4: Test the handler with httptest
The handler's job is HTTP translation: whether path parameters are parsed correctly, whether errors become the right status codes, whether the response headers and body have the right format. All of this can be tested without starting a server. To keep the example focused, here is a trimmed-down handler with only the lookup endpoint:
// Snippet: internal/order/handler.go (trimmed-down version for this article)
package order
import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
)
var ErrNotFound = errors.New("order not found")
type Order struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Total int64 `json:"total"`
Status string `json:"status"`
}
// Finder is the minimal capability the handler needs; tests swap in a fake implementation.
type Finder interface {
Get(ctx context.Context, id int64) (Order, error)
}
func NewHandler(f Finder) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "id must be a number", http.StatusBadRequest)
return
}
o, err := f.Get(r.Context(), id)
switch {
case errors.Is(err, ErrNotFound):
http.Error(w, "order not found", http.StatusNotFound)
return
case err != nil:
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(o)
})
return mux
}Note that NewHandler returns an http.Handler that includes the routing, not just a handler function. This matters: the value of r.PathValue("id") is filled in by ServeMux when it matches the pattern, so if a test calls the inner handler function directly and bypasses the mux, PathValue returns an empty string. Testing through the mux also verifies that the route pattern itself is right, including whether a wrong method returns 405. (If you really need to test a handler function on its own, call req.SetPathValue("id", "42") on the request to fill the value in by hand.)
net/http/httptest offers two ways of testing:
Figure: NewRecorder calls the handler directly like an ordinary function; NewServer starts a real server on a random local port and verifies the client's behaviour as well.
NewRecorder: the fastest and most common
httptest.NewRecorder() returns a recorder that implements http.ResponseWriter, saving the status code, headers and body the handler writes. Create a request with httptest.NewRequest (or, since Go 1.23, httptest.NewRequestWithContext, which takes a context directly), and you can call ServeHTTP directly:
// internal/order/handler_test.go
package order
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
// fakeFinder simulates data with a map; when err is non-nil it always returns that error.
type fakeFinder struct {
orders map[int64]Order
err error
}
func (f fakeFinder) Get(_ context.Context, id int64) (Order, error) {
if f.err != nil {
return Order{}, f.err
}
o, ok := f.orders[id]
if !ok {
return Order{}, ErrNotFound
}
return o, nil
}
func TestGetOrder(t *testing.T) {
finder := fakeFinder{orders: map[int64]Order{
42: {ID: 42, UserID: 7, Total: 300, Status: "pending"},
}}
tests := []struct {
name string
finder Finder
method string
path string
wantStatus int
}{
{"found", finder, http.MethodGet, "/orders/42", http.StatusOK},
{"not found", finder, http.MethodGet, "/orders/99", http.StatusNotFound},
{"bad id", finder, http.MethodGet, "/orders/abc", http.StatusBadRequest},
{"wrong method", finder, http.MethodDelete, "/orders/42", http.StatusMethodNotAllowed},
{"store failure", fakeFinder{err: errors.New("db down")}, http.MethodGet, "/orders/42", http.StatusInternalServerError},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequestWithContext(t.Context(), tc.method, tc.path, nil)
rec := httptest.NewRecorder()
NewHandler(tc.finder).ServeHTTP(rec, req)
if rec.Code != tc.wantStatus {
t.Fatalf("status = %d, want %d; body = %q", rec.Code, tc.wantStatus, rec.Body.String())
}
})
}
t.Run("response body", func(t *testing.T) {
rec := httptest.NewRecorder()
NewHandler(finder).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/orders/42", nil))
var got Order
if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
t.Fatalf("decode body: %v", err)
}
if want := (Order{ID: 42, UserID: 7, Total: 300, Status: "pending"}); got != want {
t.Errorf("body = %+v, want %+v", got, want)
}
if ct := rec.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" {
t.Errorf("Content-Type = %q", ct)
}
})
}
// Tests over a real TCP connection, verifying http.Client's behaviour as well.
func TestGetOrderOverNetwork(t *testing.T) {
srv := httptest.NewServer(NewHandler(fakeFinder{orders: map[int64]Order{
1: {ID: 1, UserID: 8, Total: 100, Status: "paid"},
}}))
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, srv.URL+"/orders/1", nil)
if err != nil {
t.Fatal(err)
}
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatalf("request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200", resp.StatusCode)
}
}This test file has three parts:
- Table-driven status code tests. Found, not found, an id that isn't a number, the wrong method, a storage failure: each case should map to the right status code. The "storage failure returns 500" case in particular is easy to produce only with a double; simulating a failure with a real database is much more trouble.
- Response content tests. The body is decoded back into an
Orderstruct and compared, rather than comparing JSON strings. String comparison fails over field order, whitespace or a trailing newline, while struct comparison cares only about what really matters. TheContent-Typeheader is checked too. - Tests over the network. See the next subsection.
NewServer: when you need a real connection
httptest.NewServer(handler) starts a real HTTP server on a random port on 127.0.0.1; srv.URL is its address, and srv.Client() returns a configured client. It is a little slower than the recorder, but it can verify behaviour that only appears with real connections: how middleware handles real requests, compression, redirects, connection timeouts, TLS (with NewTLSServer) and so on. Use t.Cleanup(srv.Close) to make sure the server is shut down when the test ends.
NewServer has another very handy use: simulating external services. The order service will later call a payment service; in tests you can use NewServer to start a fake payment service that returns prepared responses, or even deliberately delays or returns 503, to test the caller's timeout and error handling. “Timeouts, Retries and Circuit Breakers” uses this technique a lot.
Step 5: Integration tests against a real database
Doubles can prove that "each layer's logic is correct", but not that "the SQL is right", that "the transaction really rolls back", or that "the conditional update really doesn't oversell under concurrency". These can only be verified by running against a real database, which is what integration tests are for.
Integration tests need an external environment and run more slowly, so they are usually kept separate from unit tests: in everyday development go test ./... runs only the fast unit tests, and integration tests are added in CI or when needed. Go has two common ways to separate them:
| Approach | How | Characteristics |
|---|---|---|
| Build tag | //go:build integration at the top of the file, run with -tags=integration | Without the tag the whole file isn't compiled, so even the driver isn't pulled in |
testing.Short() | if testing.Short() { t.Skip() } at the start of the test, skipped with -short | The file is always compiled and runs by default; you must add -short to skip it |
This article uses a build tag, with an extra safeguard in the test: if the TEST_DATABASE_URL environment variable is not set, it calls t.Skip instead of failing. That way, even if someone adds the tag without preparing a database, they see a clear "skipped" message.
// Snippet: internal/order/repository_integration_test.go
//go:build integration
package order
import (
"database/sql"
"errors"
"os"
"sync"
"testing"
_ "github.com/jackc/pgx/v5/stdlib" // only the integration tests need a real driver
)
func openTestDB(t *testing.T) *sql.DB {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set, skipping integration tests")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatalf("open db: %v", err)
}
t.Cleanup(func() { db.Close() })
if err := db.PingContext(t.Context()); err != nil {
t.Fatalf("ping db: %v", err)
}
return db
}
// seed empties the tables and inserts one product with only stock units in stock.
func seed(t *testing.T, db *sql.DB, stock int) {
t.Helper()
ctx := t.Context()
if _, err := db.ExecContext(ctx,
`TRUNCATE order_items, orders, products RESTART IDENTITY CASCADE`); err != nil {
t.Fatalf("truncate: %v", err)
}
if _, err := db.ExecContext(ctx,
`INSERT INTO products (id, name, price, stock) VALUES (1, 'mug', 350, $1)`, stock); err != nil {
t.Fatalf("insert product: %v", err)
}
}
func countOrders(t *testing.T, db *sql.DB) int {
t.Helper()
var n int
if err := db.QueryRowContext(t.Context(), `SELECT count(*) FROM orders`).Scan(&n); err != nil {
t.Fatalf("count orders: %v", err)
}
return n
}
func TestPlaceOrder_OutOfStockRollsBack(t *testing.T) {
db := openTestDB(t)
seed(t, db, 1)
repo := NewOrderRepo(db)
if _, err := repo.PlaceOrder(t.Context(), 7, []Item{{ProductID: 1, Qty: 1}}); err != nil {
t.Fatalf("first order: %v", err)
}
_, err := repo.PlaceOrder(t.Context(), 8, []Item{{ProductID: 1, Qty: 1}})
if !errors.Is(err, ErrOutOfStock) {
t.Fatalf("second order: error = %v, want ErrOutOfStock", err)
}
if got := countOrders(t, db); got != 1 {
t.Errorf("orders = %d, want 1", got)
}
}
func TestPlaceOrder_NoOversellUnderConcurrency(t *testing.T) {
db := openTestDB(t)
seed(t, db, 1)
repo := NewOrderRepo(db)
const buyers = 20
var wg sync.WaitGroup
errs := make(chan error, buyers)
for i := range buyers {
wg.Add(1)
go func() {
defer wg.Done()
_, err := repo.PlaceOrder(t.Context(), int64(100+i), []Item{{ProductID: 1, Qty: 1}})
errs <- err
}()
}
wg.Wait()
close(errs)
var ok, outOfStock int
for err := range errs {
switch {
case err == nil:
ok++
case errors.Is(err, ErrOutOfStock):
outOfStock++
default:
t.Errorf("unexpected error: %v", err)
}
}
if ok != 1 || outOfStock != buyers-1 {
t.Errorf("ok = %d, outOfStock = %d; want 1 and %d", ok, outOfStock, buyers-1)
}
if got := countOrders(t, db); got != 1 {
t.Errorf("orders = %d, want 1", got)
}
}What these two tests verify
TestPlaceOrder_OutOfStockRollsBack: the product has only 1 unit in stock. The first order should succeed; the second should return ErrOutOfStock, and, most importantly, there must be only 1 order in the database. This directly verifies the promise of the previous article's transaction: a failed order leaves no residual data behind.
TestPlaceOrder_NoOversellUnderConcurrency: 20 goroutines race to buy the single unit in stock. If stock were deducted by "read then write", this test would very likely see several orders succeed; with the conditional update, the result must be exactly 1 success and 19 out-of-stock. Note that the goroutines don't call t.Fatalf; they send errors into a channel and the main goroutine checks them all. The number 20 is only illustrative; what matters is "at the same time".
The value of this kind of test is that it turns "we don't oversell" from a belief into a fact checked on every CI run. If someone one day rewrites the stock deduction for performance, this test immediately tells them whether they broke correctness.
Every test starts from a clean state
The most common source of flaky integration tests is data shared between tests. The example's seed empties the tables and inserts fixed data at the start of every test, so tests are unaffected by execution order. Common isolation strategies are:
- Empty and re-seed the data at the start of each test (this article's approach): simple and direct, but tests on the same database cannot run in parallel.
- Wrap each test in a transaction and roll back at the end: fast, but not applicable when the code under test opens its own transaction, as
PlaceOrderdoes. - Give each test (or each package) its own database or schema: allows parallelism, but costs more to set up.
The database itself can be started with Docker locally or in CI, with the tables created from the same migration files as production, so the test schema matches production. “Deploying a Whole Microservice System with Docker Compose” starts the database together with every service using Compose; the community also has packages that control container lifecycles directly from test code, such as testcontainers-go.
Tip: The context returned by
t.Context()is cancelled when the test ends, before the cleanup functions run. Pass it to database calls, and when a test times out or is interrupted, in-flight queries stop with it instead of leaving stuck connections behind.
Step 6: Make tests fast, stable and trustworthy
Once tests are written, they have to stay trustworthy over time. A suite that fails now and then ends up being ignored by everyone.
Always use -race
go test -race enables the data race detector, which catches, at runtime, multiple goroutines accessing the same variable without synchronisation. HTTP handlers already run in many goroutines, and with parallel subtests and concurrency tests on top, -race catches plenty of problems invisible to the naked eye. It makes tests several times slower, but it should always be on in CI. The detector only catches races that are "actually executed", so tests with concurrent scenarios (like the race-to-buy test in Step 5) are especially valuable together with -race.
Don't depend on timing or order
- Don't use
time.Sleepto wait for asynchronous results. When the machine is busy the sleep isn't long enough and the test fails; sleep too long and the whole suite slows down. Use explicit synchronisation such as channels andsync.WaitGroupinstead. For code that relies heavily on timers and timeouts,testing/synctest(since Go 1.25) provides a virtual clock that makes such tests finish instantly with deterministic results. - Inject time. Like the previous article's
now func() time.Time, make "now" a controllable input. - Use
-shuffle=onto find order dependencies. If a test only passes when run after another test, they are secretly sharing state.
Coverage is a guide, not a goal
go test -coverprofile=cover.out ./... together with go tool cover -html=cover.out shows which code was never executed. Its most useful application is finding error-handling branches that are not tested at all. But high coverage does not mean good tests: a test that just calls a function without checking the result also raises coverage. Rather than chasing a percentage, make sure every important business rule and every error mapping has a test.
Other tools worth knowing
- Golden files: when output is long (such as a generated report or complex JSON), store the expected output in a file under the
testdata/directory and compare against it, with an-updateflag to regenerate it. Thegotool ignores thetestdatadirectory, making it a good place for test data. - Fuzzing:
func FuzzXxx(f *testing.F)lets Go generate large numbers of random inputs automatically, suitable for code that must handle arbitrary input, such as parsers and validation functions. - Benchmarks:
func BenchmarkXxx(b *testing.B)measures performance, covered in detail in “Performance Tuning in Go: pprof and Benchmarks”.
Putting it together in CI
A common CI flow is: first run go vet ./... and the unit tests with go test -race ./..., a stage that should finish quickly to give developers fast feedback; then start a database container, run the migrations, and run go test -race -tags=integration -count=1 ./.... Keeping the two stages separate means no time is wasted preparing a database when the unit tests fail.
Common pitfalls
- Calling
t.Fatalin a goroutine. It only ends that goroutine; the test keeps running and may even be reported as passing. Send the error back to the main goroutine and check it there. - Bypassing the mux to test a handler function directly.
r.PathValuewill be an empty string, and a wrong route pattern goes undetected; test through the mux returned byNewHandler, or callSetPathValueby hand. - Comparing error message strings. The test breaks as soon as the wording changes; compare error identity with
errors.Isanderrors.As. - Comparing JSON strings. It fails on different field order or whitespace; decode into a struct and compare that.
- Waiting with
time.Sleep. Tests become slow and flaky; use explicit synchronisation or inject time. - Integration tests sharing data. Tests affect each other and pass only in a particular order; every test starts from a clean state.
- Only tests with doubles, no integration tests. Doubles behave exactly as you assume, so a wrong SQL statement or a badly scoped transaction goes undetected; critical database behaviour must have integration tests.
- Mocks that verify too many call details. Behaviour hasn't changed, the implementation was merely refactored, and lots of tests fail; verify outcomes first.
- Forgetting to close resources. Unclosed test servers and database connections exhaust file descriptors as the number of tests grows; use
t.Cleanup. - Not using
-race. Concurrency bugs look fine locally, then cause occasional, hard-to-reproduce errors in production.
Key takeaways
go testis built into the toolchain: test files end in_test.go, test functions areTestXxx(t *testing.T);t.Errorfkeeps going,t.Fatalfstops immediately.- The testing pyramid: many fast unit tests, a moderate number of handler tests, and a few but critical integration tests.
- Table-driven tests make adding edge cases almost free; use
t.Runfor named subtests anderrors.Isto compare errors. - Small interfaces make hand-written doubles easy; verify outcomes rather than the sequence of calls; use
t.Helperin helpers andt.Cleanupfor resources. httptest.NewRecordercalls the handler directly and is the fastest; only by testing through the mux do you getPathValueand verify routing and 405.httptest.NewServerprovides real connections and is also good for simulating external services.- Separate integration tests with the build tag
//go:build integrationandt.Skipwhen the environment is missing; each test starts from clean data and verifies rollback and no overselling under concurrency. - Use
t.Context()for a context that is cancelled when the test ends; always add-racein CI, and use-shuffle=onto find order dependencies.
Next
At this point the order service is a complete service with routing, layers, a database and tests. The next question is: as the shop grows payments, inventory and more features, should they be split into separate services, and along which lines? “When to Split: Service Boundaries and Decomposition Strategies” starts from this single service and discusses when to split and where the boundaries go.