Go testing: testing.T, subtests and table-driven tests
How go test works, how to write table-driven tests with subtests, and how to test time-dependent code by advancing a fake clock instead of sleeping.
Learning outcomes
- Write a _test.go file with TestXxx(t *testing.T) and run it with go test.
- Write a table of cases with a name, inputs and a want, and run each as a subtest with t.Run.
- Use t.Helper, t.Fatalf and t.Errorf correctly.
- Build a fake clock and advance it to test refill and window boundaries.
- Run a single test with -run and see output with -v.
Why testing matters
A rate limiter makes decisions based on state and time. A token bucket must admit requests while tokens are available, reject requests when the bucket is empty, and refill tokens as time passes. A fixed-window limiter must reset its counter at the correct boundary.
These behaviors can look correct during a quick manual check and still contain subtle bugs. A limiter might refill too early, share state between unrelated keys, or allow one extra request at a boundary.
Testing gives you a repeatable way to verify behavior. Instead of manually starting the server and sending requests every time you change the implementation, you write code that checks the expected results automatically.
Go includes a standard library testing package that makes this straightforward. You do not need to install a third-party testing framework to write ordinary Go unit tests.
A unit test checks a small piece of code in isolation. It might test a helper function, a data structure or one method on a limiter. An integration test checks how multiple components work together, such as an HTTP handler communicating with Redis.
Week 1 starts with focused unit tests. You will later use the same testing foundations to verify concurrent behavior and the complete API.
Your first Go test
Go identifies test files by their filename. A file ending in _test.go is treated as a test file and is included when you run the test command.
For example, suppose your package contains:
backend/
internal/
ratelimit/
bucket.go
bucket_test.goThe production code lives in bucket.go, while bucket_test.go contains tests for it.
A test function has a name beginning with Test and accepts one argument of type *testing.T.
package ratelimit
import "testing"
func TestAdd(t *testing.T) {
got := 2 + 3
want := 5
if got != want {
t.Fatalf("Add() = %d, want %d", got, want)
}
}The testing.T value is provided by Go when it runs the test. It gives your test functions methods for reporting failures, printing diagnostic information and managing cleanup.
The package declaration is important. This example uses package ratelimit, so the test belongs to the same package as the production code.
Running tests
Run Go commands from the backend module directory:
cd backendThe most useful test commands are:
| Command | Purpose |
|---|---|
go test | Run tests in the current package |
go test -v | Run tests and print individual test names and logs |
go test ./... | Run tests in all packages under the current module |
go test -run TestAdd | Run tests whose names match the supplied regular expression |
go test -count=1 | Run tests without using cached test results |
Go can cache successful test results. This is useful because unchanged tests do not need to run repeatedly. When investigating a problem where you need to ensure that tests execute again, use -count=1.
For example:
go test -count=1 ./internal/ratelimitA successful run prints output similar to:
ok github.com/yashdagar/zomato-prep/backend/internal/ratelimit 0.004sThe ok indicates that the package's tests passed. The duration is how long the test command took for that package.
If a test fails, Go reports the package, test name, source file and line number where the failure was reported.
Reporting failures
The testing package gives you several methods for reporting problems. The two most important categories are fatal failures and non-fatal failures.
Fatal failures
Use t.Fatal or t.Fatalf when the test cannot continue meaningfully after a failed check.
t.Fatalreports the supplied values and stops the current test function.t.Fatalfformats a message using a format string and stops the current test function.
For example:
func TestLookup(t *testing.T) {
value, ok := lookup("restaurant-17")
if !ok {
t.Fatalf("lookup() did not find restaurant-17")
}
if value != "Restaurant One" {
t.Fatalf("lookup() = %q, want %q", value, "Restaurant One")
}
}If the lookup fails, continuing with the returned value might produce a misleading second failure. Stopping immediately makes the actual problem clearer.
Non-fatal failures
Use t.Error or t.Errorf when the test can continue checking other independent conditions.
t.Errorreports the supplied values but continues the test.t.Errorfformats a message, reports it and continues the test.
For example:
func TestResponseFields(t *testing.T) {
status := 200
contentType := "application/json"
if status != 200 {
t.Errorf("status = %d, want 200", status)
}
if contentType != "application/json" {
t.Errorf("Content-Type = %q, want application/json", contentType)
}
}Both checks are independent. If the status is wrong, there is still value in checking the content type.
A useful rule is:
- Use
Fatalwhen a failed condition makes the remaining checks invalid or unsafe. - Use
Errorwhen other checks can still provide useful information.
Do not use Fatal for every assertion just because it is convenient. Stopping too early can hide additional failures.
Format useful failure messages
A good failure message tells you three things:
- What operation was tested.
- What value was actually returned.
- What value was expected.
For example:
t.Errorf("Allow(%q) = %v, want %v", key, got, want)This is more useful than:
t.Error("wrong result")A test should help you diagnose a defect without requiring you to reproduce it manually.
Table-driven tests
A limiter has many possible inputs and outcomes. Writing a separate test function for every case quickly becomes repetitive.
A table-driven test stores related cases in a slice and runs the same test logic for each case.
Each entry describes one scenario. Common fields include:
name: A short description of the case.- Inputs: Values passed to the function.
want: The expected result.
Consider a small helper that calculates the number of tokens after lazy refill:
package ratelimit
func refillTokens(tokens, elapsedSeconds, refillPerSec, capacity float64) float64 {
updated := tokens + elapsedSeconds*refillPerSec
if updated > capacity {
return capacity
}
return updated
}This function is intentionally small. It gives us something concrete to test without implementing the complete token bucket exercise.
A table-driven test might look like this:
package ratelimit
import "testing"
func TestRefillTokens(t *testing.T) {
tests := []struct {
name string
tokens float64
elapsedSeconds float64
refillPerSec float64
capacity float64
want float64
}{
{
name: "refills partially",
tokens: 2,
elapsedSeconds: 1,
refillPerSec: 1,
capacity: 5,
want: 3,
},
{
name: "caps at capacity",
tokens: 4,
elapsedSeconds: 3,
refillPerSec: 2,
capacity: 5,
want: 5,
},
{
name: "no elapsed time",
tokens: 2,
elapsedSeconds: 0,
refillPerSec: 1,
capacity: 5,
want: 2,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := refillTokens(
tt.tokens,
tt.elapsedSeconds,
tt.refillPerSec,
tt.capacity,
)
if got != tt.want {
t.Errorf("refillTokens() = %v, want %v", got, tt.want)
}
})
}
}The tests slice contains three scenarios. The loop runs the same calculation and assertion for each entry.
Understanding subtests
The call to t.Run creates a subtest. A subtest is a named test nested inside another test.
Here, each table entry becomes a separate subtest:
TestRefillTokens
refills partially
caps at capacity
no elapsed timeThis gives each case its own name in the test output. If one case fails, you can identify the scenario immediately.
For example:
go test -v -run TestRefillTokensPossible output:
=== RUN TestRefillTokens
=== RUN TestRefillTokens/refills_partially
=== RUN TestRefillTokens/caps_at_capacity
=== RUN TestRefillTokens/no_elapsed_time
--- PASS: TestRefillTokens (0.00s)
--- PASS: TestRefillTokens/refills_partially (0.00s)
--- PASS: TestRefillTokens/caps_at_capacity (0.00s)
--- PASS: TestRefillTokens/no_elapsed_time (0.00s)
PASSIf the capacity case fails, the output identifies TestRefillTokens/caps_at_capacity rather than just telling you that a large test function failed.


Loop variables in Go 1.22
Older Go code often needed an extra step to capture the loop variable before passing it into a closure. This was important when subtests ran later or in parallel.
Go 1.22 changed loop variable semantics for packages using the Go 1.22 language version or newer. Each iteration gets its own loop variable, so the table-driven pattern shown above is safe.
You may still encounter older code that uses:
tt := ttThat assignment was traditionally used to create a distinct variable for each iteration. With Go 1.22 semantics, it is unnecessary in the example above.
This does not mean you can ignore closure behavior in every situation. Understand which variable a closure captures, especially when working with code written for older Go versions.
Testing functions that return errors
Many Go functions return more than one value. A common pattern is a result followed by an error:
func parseLimit(value int) (int, error) {
if value <= 0 {
return 0, errors.New("limit must be positive")
}
return value, nil
}A test should check both return values.
package ratelimit
import (
"errors"
"testing"
)
func TestParseLimit(t *testing.T) {
got, err := parseLimit(10)
if err != nil {
t.Fatalf("parseLimit(10) returned error: %v", err)
}
if got != 10 {
t.Errorf("parseLimit(10) = %d, want 10", got)
}
_, err = parseLimit(0)
if err == nil {
t.Fatal("parseLimit(0) returned nil error, want an error")
}
}The success case verifies the returned value and confirms that no error occurred. The failure case verifies that an invalid input produces an error.
When the exact error matters, check it deliberately. If the function returns a sentinel error, use errors.Is rather than comparing error strings.
For example:
if !errors.Is(err, ErrInvalidLimit) {
t.Fatalf("error = %v, want ErrInvalidLimit", err)
}Error messages can change. Sentinel errors provide a stable value that callers and tests can identify.
Helpers and t.Helper
Tests often repeat the same setup and assertions. A helper function can remove that duplication.
For example:
func assertFloat64(t *testing.T, got, want float64) {
t.Helper()
if got != want {
t.Fatalf("got %v, want %v", got, want)
}
}The call to t.Helper() marks the function as a test helper. If it reports a failure, Go points to the helper's caller rather than treating the helper's internal assertion line as the main failure location.
This makes failure reports easier to understand.
Use helpers when they make tests clearer. Avoid building a large testing framework of your own for a small package.
Testing time without waiting
Rate limiters depend on elapsed time. Calling the real clock in a test makes the result dependent on how long the test takes to execute.
For example, a test that waits one second to verify token refill is slower and less predictable than necessary.
Lesson 1.10 introduced an injected clock. We can use the same idea in tests with a small fake clock.
A fake clock is a controllable replacement for the real clock. It returns a time value stored in a field, and the test advances that value explicitly.
For this lesson, a plain struct is sufficient:
package ratelimit
import "time"
type fakeClock struct {
current time.Time
}
func (f *fakeClock) Now() time.Time {
return f.current
}
func (f *fakeClock) Advance(d time.Duration) {
f.current = f.current.Add(d)
}The Now method returns the current simulated time. The Advance method moves it forward by a chosen duration.
You can pass the method as a function value:
clock := &fakeClock{
current: time.Date(2026, time.January, 1, 12, 0, 0, 0, time.UTC),
}
now := clock.NowThe now variable has the type func() time.Time. It can be passed to the token bucket or fixed-window constructor:
limiter := NewTokenBucket(5, 1, now)This example shows the dependency wiring. It does not provide the implementation of the exercise's limiter.
Advancing time between requests
Suppose a test needs to check behavior at several points:
clock := &fakeClock{
current: time.Date(2026, time.January, 1, 12, 0, 0, 0, time.UTC),
}
now := clock.Now
clock.Advance(time.Second)
clock.Advance(500 * time.Millisecond)
_ = now()The clock moves forward immediately. No real waiting is involved.
A test can therefore make requests, advance the fake clock and make more requests while controlling exactly how much time has passed.


A fake clock in table-driven tests
A table can describe how much time to advance before each request and what result to expect.
For example, a made-up counter limiter could be tested using steps with these fields:
steps := []struct {
name string
advance time.Duration
want bool
}{
{
name: "initial request",
advance: 0,
want: true,
},
{
name: "request after one second",
advance: time.Second,
want: true,
},
}The test loops over the steps, advances the clock and checks the result of the operation.
This is the same pattern used by the supplied limiter tests: each step describes a time change and an expected admission decision.
For the course exercises, you will use the fake clock to verify behaviors such as:
- A token bucket allows an initial burst up to its capacity.
- A token becomes available after enough time has elapsed.
- Different keys have independent state.
- A fixed-window counter resets at a window boundary.
Do not use time.Sleep to test these behaviors. Sleeping makes tests slower and introduces timing uncertainty that the fake clock avoids.
The fake clock in this lesson is deliberately simple. When tests begin exercising concurrent access in the next lessons, the fake clock itself will need synchronization so that advancing and reading its state are safe.
Same-package and external tests
A test file can use the same package name as the production code:
package ratelimitThis is called a same-package test. It can access unexported identifiers, meaning names that begin with a lowercase letter.
That is useful when you need to test internal helpers or inspect package state without exposing those details as part of the public API.
An external test can instead use:
package ratelimit_testThis is a separate package. It can access only exported identifiers through the package's public API.
External tests are useful for checking whether the package behaves correctly from the perspective of a normal consumer. Same-package tests are useful when internal behavior needs focused verification.
Choose the package style based on what the test needs to verify. Do not export internal implementation details just to make them accessible to a test.
Test files in this course repository
The course repository already contains tests for the exercises. They are organized by exercise identifier so that you can run the tests for one implementation task without running every test in the project.
You will encounter names such as:
func TestW1B2_TokenBucket(t *testing.T) {
}The W1B2 portion identifies Week 1, exercise step B2. The rest describes the behavior being tested.
The Makefile provides a focused command:
make test W=1B2This runs the test target for that exercise. It is useful while you are implementing one step because you get faster feedback than running the entire repository test suite.
You can also run all tests with:
make testFollow the exercise's instructions for the expected command and working directory.
Do not redeclare provided test identifiers
The provided limiter_test.go may already define a fakeClock type and test functions such as TestW1B2_TokenBucket.
If you add another declaration with the same name in the same package, Go reports a duplicate declaration error.
Do not copy the provided fake clock or test function into another test file under the same package. Use the supplied definitions. If you need an additional helper for your own experiments, give it a different name.
You are expected to implement the production code that the tests exercise, not duplicate the tests themselves.
Other useful testing tools
The testing package provides several utilities that become useful as projects grow.
t.TempDir
t.TempDir() creates a temporary directory for a test. Go removes it automatically after the test and its subtests finish.
It is useful when testing code that reads or writes files.
t.Cleanup
t.Cleanup registers a function that runs after the test and its subtests complete.
Use it to release resources or restore state created during a test.
testdata
A directory named testdata is commonly used to store test fixtures. A fixture is sample input that a test reads, such as JSON documents, text files or sample images.
Go tooling treats testdata specially, so it is a convenient place for files needed by tests without treating them as ordinary package source files.
Parallel tests
Go also supports parallel tests through t.Parallel(). These tests can run alongside other tests, which can reduce execution time.
However, parallel tests introduce additional concerns around shared state and cleanup. You will encounter concurrency and the race detector in the next lesson, so do not add parallel execution to the limiter tests yet.
Reading failures and improving tests
A passing test tells you that the tested cases behaved as expected. It does not prove that the implementation is correct for every possible input.
Good tests cover meaningful boundaries and failure cases, not just the most obvious successful input.
For a limiter, useful cases include:
- The first request for a new key.
- The final request that consumes the available allowance.
- The first request that should be rejected.
- A request after enough time has passed to restore capacity.
- A request using a different key.
- A request exactly at a fixed-window boundary.
- Invalid configuration, if the constructor or exercise contract defines how to handle it.
When a test fails, read the test name first. If it is a subtest, the case name often tells you exactly which scenario failed.
Then read the reported file and line number, compare the actual value with the expected value, and inspect the production code involved in that behavior.
Do not change an expected value simply to make a test pass. First establish whether the test or the implementation is wrong. In this course, the supplied tests represent the expected exercise contract.
Knowledge assessment
Which filename and function signature follow Go's requirements for a basic test?
Practical applications
- Exercise 1.15: Write deterministic tests for the token bucket and fixed-window limiter using table-driven cases and a fake clock.
- Every exercise with provided tests: Run the focused test target with
make test W=...to verify your implementation against the repository's expected behavior.
References
Everything above is explained on this page; these are where it comes from (Go 1.2x).