Testing and benchmarks
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
Testing is part of the toolchain
In Go you do not install a test framework. The testing package and the go test command come with the language. A test is a function in a file whose name ends in _test.go, with a name that starts with Test and one parameter of type *testing.T.
The code under test
// pricing/pricing.go
package pricing
import (
"errors"
"fmt"
)
var ErrInvalidPercent = errors.New("percent must be between 0 and 100")
// ApplyDiscount reduces an amount (in paisa) by a percentage.
func ApplyDiscount(amount int64, percent int) (int64, error) {
if percent < 0 || percent > 100 {
return 0, fmt.Errorf("discount %d: %w", percent, ErrInvalidPercent)
}
return amount - amount*int64(percent)/100, nil
}
// WithTax adds tax given in basis points (1700 = 17%).
func WithTax(amount int64, basisPoints int64) int64 {
return amount + amount*basisPoints/10000
}
A table-driven test
// pricing/pricing_test.go
package pricing
import (
"errors"
"testing"
)
func TestApplyDiscount(t *testing.T) {
tests := []struct {
name string
amount int64
percent int
want int64
wantErr error
}{
{"no discount", 100000, 0, 100000, nil},
{"ten percent", 100000, 10, 90000, nil},
{"full discount", 100000, 100, 0, nil},
{"negative percent", 100000, -5, 0, ErrInvalidPercent},
{"too large", 100000, 101, 0, ErrInvalidPercent},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := ApplyDiscount(tc.amount, tc.percent)
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)
}
})
}
}
func TestWithTax(t *testing.T) {
if got := WithTax(100000, 1700); got != 117000 {
t.Errorf("WithTax = %d, want 117000", got)
}
}
func BenchmarkApplyDiscount(b *testing.B) {
for b.Loop() {
ApplyDiscount(123456, 15)
}
}
Run the tests from the module root:
go test ./...
go test -v ./pricing
go test -run TestApplyDiscount/ten ./pricing
go test -cover ./...
go test -race ./...
A passing run prints ok example.com/shop/pricing 0.003s. A failing one shows the test name, the file and line, and your message.
How the test works
This is the table-driven style, the most common pattern in Go. We describe each case as a row in a slice of structs, then loop over the rows. Adding a new case takes one line, and every case runs even if an earlier one fails. t.Run starts a subtest with its own name, so the output shows exactly which row failed, and you can run just one with -run.
There are two ways to report failure. t.Errorf records the failure and continues, so you see all problems. t.Fatalf records it and stops the current test immediately, which is right when later checks would make no sense, like using a result after an unexpected error. Good failure messages say what you got and what you wanted, in the same order every time. I use got ..., want ... everywhere.
We compare the error with errors.Is, not by text. A nil expected error also works with errors.Is(nil, nil), which returns true, so one comparison handles both the success and failure rows.
Test files and packages
Test files live next to the code. If the test declares the same package, package pricing, it can reach unexported names. If it declares package pricing_test, it can only use the public API, like a real user would. Both are normal, and many projects use the second style for the main tests.
Helpers and temporary files
func newTestStore(t *testing.T) *Store {
t.Helper() // report failures at the caller's line
dir := t.TempDir() // deleted automatically after the test
s, err := OpenStore(filepath.Join(dir, "data.json"))
if err != nil {
t.Fatal(err)
}
return s
}
t.Helper() marks a function as a helper so failure lines point at the test that called it. t.TempDir() gives a fresh directory per test. t.Cleanup(func(){...}) registers cleanup code. In Go 1.24 and later, t.Context() gives a context that is cancelled when the test finishes. Prefer these to hand-written setup and teardown.
Fakes through interfaces
Because interfaces are implicit, you can test code that talks to the outside world by giving it a small fake. If OrderService needs a Notifier, a test can pass a struct that records the messages it received. No mocking library is required. This is one of the best reasons to keep interfaces small.
Benchmarks
A benchmark is a function named BenchmarkXxx taking *testing.B. Go runs the loop many times and reports the time per operation. In Go 1.24 and later, the loop is for b.Loop() { ... }. On older versions you write for i := 0; i < b.N; i++. Run them with:
go test -bench=. -benchmem ./pricing
The output has lines like BenchmarkApplyDiscount-8 300000000 3.9 ns/op 0 B/op 0 allocs/op. The numbers depend on your machine. The last two columns, from -benchmem, show memory allocated per operation, and allocations are often the thing to reduce. To compare before and after a change, save the output of both runs and use the benchstat tool, since a single run is noisy.
Common mistakes
- Naming slip. The file must end in
_test.go, and the function must start withTestfollowed by a capital letter or underscore.Testdiscountis not run. - Capturing the loop variable in parallel subtests. In Go 1.22 and later each iteration has its own copy, so it is safe. On older versions you needed
tc := tc. - Testing implementation details. Tests that break whenever you refactor are a burden. Test behaviour.
- Using time.Sleep to wait for goroutines. It makes tests slow and flaky. Use channels, WaitGroups or contexts.
Try it yourself
Write a function SplitBill(total int64, people int) ([]int64, error) that divides a total in paisa between people so that the parts add up exactly to the total, with the remainder spread across the first few people. Write a table-driven test with at least six cases, including zero people. Then write a benchmark with 10 and 10,000 people.
// pricing/pricing_test.go
package pricing
import (
"errors"
"testing"
)
func TestApplyDiscount(t *testing.T) {
tests := []struct {
name string
amount int64
percent int
want int64
wantErr error
}{
{"no discount", 100000, 0, 100000, nil},
{"ten percent", 100000, 10, 90000, nil},
{"full discount", 100000, 100, 0, nil},
{"negative percent", 100000, -5, 0, ErrInvalidPercent},
{"too large", 100000, 101, 0, ErrInvalidPercent},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := ApplyDiscount(tc.amount, tc.percent)
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)
}
})
}
}
func TestWithTax(t *testing.T) {
if got := WithTax(100000, 1700); got != 117000 {
t.Errorf("WithTax = %d, want 117000", got)
}
}
func BenchmarkApplyDiscount(b *testing.B) {
for b.Loop() {
ApplyDiscount(123456, 15)
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account