Testing in Go: go test, Table-Driven Tests, Failures and Coverage
Write tests the Go way with the testing package and table-driven cases, run go test to see a real failure with its file and line, fix the bug, and measure coverage, with expected values taken from the rules.
In this lesson you will
- Write tests in _test.go files
- Use table-driven tests with t.Run
- Read a failing test
- Measure coverage
About 28 minutes
The discount that vanished
After a change to the price list, Mei’s customers stop getting the discount on long storage periods, and nobody notices for a week. Tests prevent that. Go includes a testing framework in the standard library and in the go tool, with no extra downloads. A test lives in a file whose name ends in _test.go, in the same package as the code, and is a function named TestSomething that takes a *testing.T. Calling t.Errorf records a failure and carries on, t.Fatalf stops that test, and go test finds and runs every test in the package.
The Go habit is the table-driven test: a slice of cases, each with inputs and the expected output, and a loop that runs them all, usually with t.Run so that every case gets its own name in the report. Adding a case means adding one line. Good cases include the typical value and every boundary of every rule: for a discount that starts at five days, the cases around it are 4, 5 and 6. The expected values must come from the written rules, not from running the code. The flag -v prints each test, -run selects tests by name, and -cover reports the share of statements that the tests executed.
| Tool | Meaning |
|---|---|
| func TestX(t *testing.T) | A test, in a file ending in _test.go |
| t.Errorf, t.Fatalf | Report a failure, continue or stop |
| t.Run(name, func(t *testing.T) {…}) | A named sub-test |
| go test -v | Show each test and its result |
| go test -cover | Show statement coverage |
package main
import "fmt"
// Price returns the storage price: 3.00 per day, 10% off from 5 days.
func Price(days int) float64 {
p := float64(days) * 3.0
if days > 5 { // BUG: the rule says 5 or more
p *= 0.9
}
return p
}
func main() { fmt.Printf("%.2f\n", Price(5)) }
package main
import (
"math"
"testing"
)
func TestPrice(t *testing.T) {
cases := []struct {
name string
days int
want float64
}{
{"0 days", 0, 0.0},
{"1 days", 1, 3.0},
{"4 days", 4, 12.0},
{"5 days", 5, 13.5},
{"6 days", 6, 16.2},
{"10 days", 10, 27.0},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := Price(c.days)
if math.Abs(got-c.want) > 1e-9 {
t.Errorf("Price(%d) = %.2f, want %.2f", c.days, got, c.want)
}
})
}
}
=== RUN TestPrice
=== RUN TestPrice/0_days
=== RUN TestPrice/1_days
=== RUN TestPrice/4_days
=== RUN TestPrice/5_days
price_test.go:25: Price(5) = 15.00, want 13.50
=== RUN TestPrice/6_days
=== RUN TestPrice/10_days
--- FAIL: TestPrice (0.00s)
--- PASS: TestPrice/0_days (0.00s)
--- PASS: TestPrice/1_days (0.00s)
--- PASS: TestPrice/4_days (0.00s)
--- FAIL: TestPrice/5_days (0.00s)
--- PASS: TestPrice/6_days (0.00s)
--- PASS: TestPrice/10_days (0.00s)
FAIL
exit status 1
FAIL demo 0.00s
The run shows five passing cases and one failure, “5 days”, with the message “Price(5) = 15.00, want 13.50” and the file and line of the t.Errorf call in front of it. The go tool exited with a non-zero code, 1, which is what a continuous integration system looks for. The cases for 4 and 6 days passed, so a test of only typical values would have missed the bug: the code uses days > 5 where the rule says 5 or more, and only the boundary case at exactly 5 days exposes it. The sub-test names make the failing case easy to find and to rerun with go test -run “TestPrice/5_days”.
package main
import "fmt"
// Price returns the storage price: 3.00 per day, 10% off from 5 days.
func Price(days int) float64 {
p := float64(days) * 3.0
if days >= 5 {
p *= 0.9
}
return p
}
func main() { fmt.Printf("%.2f\n", Price(5)) }
package main
import (
"math"
"testing"
)
func TestPrice(t *testing.T) {
cases := []struct {
name string
days int
want float64
}{
{"0 days", 0, 0.0},
{"1 days", 1, 3.0},
{"4 days", 4, 12.0},
{"5 days", 5, 13.5},
{"6 days", 6, 16.2},
{"10 days", 10, 27.0},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := Price(c.days)
if math.Abs(got-c.want) > 1e-9 {
t.Errorf("Price(%d) = %.2f, want %.2f", c.days, got, c.want)
}
})
}
}
=== RUN TestPrice
=== RUN TestPrice/0_days
=== RUN TestPrice/1_days
=== RUN TestPrice/4_days
=== RUN TestPrice/5_days
=== RUN TestPrice/6_days
=== RUN TestPrice/10_days
--- PASS: TestPrice (0.00s)
--- PASS: TestPrice/0_days (0.00s)
--- PASS: TestPrice/1_days (0.00s)
--- PASS: TestPrice/4_days (0.00s)
--- PASS: TestPrice/5_days (0.00s)
--- PASS: TestPrice/6_days (0.00s)
--- PASS: TestPrice/10_days (0.00s)
PASS
coverage: 80.0% of statements
ok demo 0.00s
After the fix all 6 cases pass, and the coverage line reports 80.0 percent of statements. The missing part is main, which the test never runs, and that shows what coverage tells you: which lines were executed, not whether they were tested well. The expected values in the table, 0 days: 0.0, 1 days: 3.0, 4 days: 12.0, 5 days: 13.5, 6 days: 16.2, 10 days: 27.0, came from the written rule, 3.00 per day with 10 percent off from 5 days, and were computed in Python before the program ran.
Check by hand: 4 days cost 12.0. 5 days cost 15.00 and 10 percent off gives 13.5. 6 days cost 18.00, less 10 percent is 16.2, and 10 days cost 30.00, less 10 percent, 27.0. Zero days cost nothing.
Break the code on purpose once, as this lesson did, and make sure a test notices. Then you know that the test checks something.
For each limit, test the value just below, exactly at and just above it. Table-driven tests make it a one-line addition per case, and they read like documentation of the rule.
Every program in this lesson was built and run with Go 1.24 while the course was written. Go releases twice a year, so check go.dev for the current version and release notes. The test output was run with go test -v, with timings replaced by placeholders.
Practice
Add a rule for parcels over 20 days and test its boundary. Write a test that checks an error return with errors.Is. Run go test -race -cover ./… and open the coverage report in a browser with go tool cover -html.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What must a test file be called?
- test.go
- A name starting with Test
- A name ending in _test.go
- main_test.txt
go test finds it by name.
What is a table-driven test?
- A test of a database
- A slice of cases run in a loop
- A test for tables in HTML
- A test that sorts
Adding a case is one line.
Which case found the bug?
- 10 days
- 5 days, the boundary
- 0 days
- 4 days
The code used > where the rule says >=.
What does -cover report?
- The share of statements executed by tests
- The test speed
- The number of bugs
- The file size
It does not measure test quality.
Where should expected values come from?
- The written rules
- The output of the code
- A guess
- The test name
Otherwise the test copies the bug.
Summary
- Tests live in _test.go files and use the testing package.
- Table-driven tests with t.Run cover many cases compactly.
- Boundary cases find off-by-one bugs.
- go test -cover shows which statements ran.
Questions
Do I need a test library?
Not to start. The testing package covers most needs, and libraries such as testify add assertion helpers, which many teams find convenient.
What are benchmarks?
Functions named BenchmarkX in test files that go test -bench runs to measure speed. They are worth using before you optimise.
How do I test code that uses the network?
Use interfaces and fakes, or the net/http/httptest package, which the next lesson uses.
