The Programming Shortcut: Testing
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about testing: writing code that checks your code.
You already test your code. You have done it since your first program.
You write a function, you run the program, and you look at what it printed. Is that the right number? Does the message read properly? If it looks wrong, you fix something and run it again. That looking is testing. It’s careful, it works, and it has one weakness: it only happens while you are watching, and only for the things you remember to look at.
A test is that same act written down. It’s a small piece of code that calls your code with an input you chose, compares the answer with the answer you expected, and complains if they differ. Once it’s written, the computer does the looking, every time, for every case you ever thought of, in well under a second. You stop re-checking by eye things you already checked last week.
The rest of this piece is about doing that well. Testing is a working habit, not
a language feature, so the idea isn’t tied to a language. This piece uses Go,
because Go builds testing into its own command and keeps it plain. There is no
testing library to choose, no configuration file, no plugin. You write a function
with a particular name in a file with a particular name, and you type go test.
If you don’t have Go yet, the
installer and instructions are here. You don’t need to know Go to follow along. If you can read a function and an if,
you can read every test in this piece.
A test is just a program that checks
Before any testing tool appears, here’s a test with no tool at all. It’s an
ordinary Go program. The function count is supposed to say how many of something
there are: “3 files”, “1 file”. The rest of the program checks it.
package main
import (
"fmt"
"os"
)
func count(n int, word string) string {
return fmt.Sprintf("%d %ss", n, word)
}
func main() {
got := count(1, "file")
want := "1 file"
if got != want {
fmt.Printf("count(1, \"file\") = %q, want %q\n", got, want)
os.Exit(1)
}
fmt.Println("ok")
}
(fmt.Sprintf builds a string from a pattern, the way printf or an f-string
does. %d is a number, %s is a string, %q is a string shown in quotes.)
Save it as main.go and run it with go run main.go. It prints:
count(1, "file") = "1 files", want "1 file"
exit status 1
Look at the shape, because every test you will ever write has it. You call the code with an input you picked. You hold the answer you got next to the answer you want. If they differ, you say so loudly, with enough detail to know what went wrong, and you end with a failing status so that whatever ran you knows too.
That’s it. Testing tools add convenience on top of this shape: a standard place to put the checks, a way to run all of them with one command, a tidy report. None of them change the shape.
Notice also that this check found a real bug. count always adds an “s”, and one
file isn’t “1 files”. You might have spotted that by reading the code. You might
not have, on a busy day, in a longer function. The check doesn’t get busy.
Edit, then go test
Go’s version of this lives in its own files, so your checks never get mixed into your program. Make a folder for a small package (Go’s word for a folder of code that belongs together) and give it a module name, which is how Go identifies a project:
mkdir plural
cd plural
go mod init plural
Now two files. The first is the code, plural.go:
package plural
import "fmt"
func Count(n int, word string) string {
return fmt.Sprintf("%d %ss", n, word)
}
(The capital C matters in Go: names that start with a capital letter can be used from outside the package.)
The second is the test, plural_test.go:
package plural
import "testing"
func TestCount(t *testing.T) {
got := Count(3, "file")
want := "3 files"
if got != want {
t.Errorf("Count(3, \"file\") = %q, want %q", got, want)
}
}
Three conventions do all the work. A file whose name ends in _test.go is a test
file: go test compiles it, and an ordinary build leaves it out. A function whose
name starts with Test and takes a *testing.T is a test. And t.Errorf is how a
test complains: it prints your message and marks the test as failed.
Run it:
$ go test
PASS
ok plural 0.002s
Edit the code or the tests, type go test, read the answer. It’s the same rhythm
you already have when you run a program and look at the output, with the looking
done for you. You will come back to it after every change in this
piece.
Add -v (for “verbose”) to see each test by name as it runs:
$ go test -v
=== RUN TestCount
--- PASS: TestCount (0.00s)
PASS
ok plural 0.001s
Red first
The test passes, and the bug from the first section is still sitting in Count.
Of course it passes: it only asks about three files. A test can only find the
mistakes it asks about.
So ask. Add a second test to plural_test.go, below the first:
func TestCountOne(t *testing.T) {
got := Count(1, "file")
want := "1 file"
if got != want {
t.Errorf("Count(1, \"file\") = %q, want %q", got, want)
}
}
Run it again:
$ go test
--- FAIL: TestCountOne (0.00s)
plural_test.go:17: Count(1, "file") = "1 files", want "1 file"
FAIL
exit status 1
FAIL plural 0.002s
This is good news, and you’ll learn to feel that way about it. The failure names the test, the file and line, the input, what came back and what should have. That’s a better bug report than most people write by hand.
Now fix the code:
func Count(n int, word string) string {
if n == 1 {
return fmt.Sprintf("%d %s", n, word)
}
return fmt.Sprintf("%d %ss", n, word)
}
Run go test again, and it says PASS.
What just happened has a name among programmers: red, green. Red is the failing test, green is the passing one, after the names many test tools give their colors. Writing the test first, watching it fail, and only then fixing the code proves two things at once. It proves the bug was real, and it proves the test can tell the difference. A test that has never failed in front of you hasn’t shown you either.
The test also stays. From now on, if anyone (including you, six months from now)
breaks the one-file case, go test says so the next time it runs. A test written
to catch a bug that already happened once is called a regression test, because it
stops the code from regressing, sliding back to a state it was in before. Bugs do come
back, usually when someone tidies up the code that fixed them.
Many cases, one test
You now have two tests that are the same five lines with different numbers in them. A third would make three. When tests repeat like that, the thing that varies is the data, so make the data the visible part.
This is called a table-driven test: a list of cases, each with its inputs and the answer you want, and one loop that checks them all. Replace both tests with this one:
func TestCount(t *testing.T) {
cases := []struct {
n int
word string
want string
}{
{3, "file", "3 files"},
{1, "file", "1 file"},
{0, "file", "0 files"},
{2, "box", "2 boxes"},
}
for _, c := range cases {
got := Count(c.n, c.word)
if got != c.want {
t.Errorf("Count(%d, %q) = %q, want %q", c.n, c.word, got, c.want)
}
}
}
The list is a slice (Go’s growable array) of records that have no name of their
own, written out in place: each {3, "file", "3 files"} is one row. If your language would use an array
of objects or tuples here, it’s the same thing.
Run it:
$ go test
--- FAIL: TestCount (0.00s)
plural_test.go:19: Count(2, "box") = "2 boxs", want "2 boxes"
FAIL
exit status 1
FAIL plural 0.002s
Look at what that table did. Adding a case cost one line, so you added the cases that came to mind: zero, which English treats as plural, and a word that doesn’t just take an “s”. The second one failed. You’d never have written five more lines to check “box”. You will happily write one.
Here’s a fix that handles the common endings. It needs the strings package, so
this is the whole of plural.go now:
package plural
import (
"fmt"
"strings"
)
func Count(n int, word string) string {
if n == 1 {
return fmt.Sprintf("%d %s", n, word)
}
for _, ending := range []string{"s", "x", "z", "ch", "sh"} {
if strings.HasSuffix(word, ending) {
return fmt.Sprintf("%d %ses", n, word)
}
}
return fmt.Sprintf("%d %ss", n, word)
}
Run go test, and it’s green.
Then think about “mouse”. Or “child”. Your function says “2 mouses”, and now you
have a choice to make: teach it more English, take the plural form as a second
argument, or decide that this function is for simple words and say so. A test is
where you write that decision down. Add {2, "mouse", "2 mouses"} and you’ve
recorded that this is known and accepted. Add {2, "mouse", "2 mice"} and you’ve
committed to fixing it. Either way, the next person to read the tests knows what
the function promises, without reading its code.
That last point is the quiet reason tests matter beyond catching bugs. The table is
the clearest description of what Count does that exists anywhere. It’s a
description that can’t go out of date, because the moment it stops being true,
go test fails.
Choosing what to test
You can’t test every input. Count takes any number and any word; there are more
combinations than there are atoms to write them on. So every test is a sample, and
the skill is in choosing the sample.
Bugs gather at edges. When you pick cases, reach for the places where the behavior changes or where the code has to make a decision: zero, one and many; the first item and the last; an empty string; a value exactly at a limit and one past it. These are called edge cases or boundary cases, and most of your rows should be them. The middle of the range almost always works. That’s where you tried it by hand.
Look at the shape of the code, too. Every if is a place where two kinds of input
get different treatment, and each kind deserves at least one row. Count has a
branch for one, a branch for the special endings, and a fallthrough. The table above
reaches all three.
And test what the code promises, not how it keeps the promise. Every test in this
piece calls Count and looks at its answer. None of them peek at how it builds the
string. That means you can rewrite the inside of Count any way you like (with a
switch, with a map of endings, with something cleverer) and the tests still tell
you whether it works. Changing how code is written without changing what it does is
called refactoring, and tests are what make it safe. Without them, every tidy-up
is a small gamble.
Against the grain
Some languages and testing libraries give you a vocabulary of assertions, special
functions that check something and fail the test if it’s false: assertEqual(a, b),
expect(a).toBe(b), assert a == b. Go has none of them. You write an ordinary
if, and you write the failure message yourself.
That feels primitive the first time, and it’s on purpose. The test is plain Go, so
there’s nothing new to learn, and the message says what you decided it should say.
The cost is that writing a good message is your job. A test that fails with wrong answer has thrown away the information you need. A test that fails with
Count(2, "box") = "2 boxs", want "2 boxes" has fixed half the bug for you. Go’s
habit of writing the call, then what you got, then what you want, carries into any
language.
Go also gives you two ways to fail. t.Errorf records the failure and carries on,
so one run can report every row in a table that’s wrong. t.Fatalf records it and
stops that test immediately, which you want when going on makes no sense, such as
when the setup the rest of the test needs didn’t work.
The deeper thing to give up is a guarantee you may have been hoping for. Passing tests don’t prove a program is correct. They prove it’s correct for the cases you wrote. A bug that gets past a green test run is in a case nobody thought to check. Tests make you much more confident; they never make you certain.
Beware of a test you have never seen fail. It’s an easy way for a test to go
wrong, and an invisible one: a test with a typo that compares a value to itself, a
loop over an empty table, a check on the wrong variable. Each of these passes
forever and checks nothing. So make every new test fail once, on purpose, before you
trust it. If you wrote it for a bug, run it before the fix. If you wrote it for
working code, break the code for a moment (change a 1 to a 2, flip a <) and
watch the test catch it. Thirty seconds, every time. The alternative is a green
report you can’t believe, which is worse than no report, because it looks like one
you can.
A small project: which version is newer?
Software versions look like 1.9.0 and 1.10.2, and programs compare them all the
time to decide whether an update is available. It looks like a job for ordinary
string comparison. Here’s the version you might write in a hurry:
func Newer(a, b string) bool {
return a > b
}
And here’s one row of a table that tests it:
{"1.10.0", "1.9.0", true},
It fails. Strings compare character by character, and at the third character "1"
comes before "9", so as text "1.10.0" sorts before "1.9.0". Version 1.10 is
newer, and the hurried function says it’s older. Every test in the middle of the
range would have passed, which makes it an easy bug to ship. It’s a boundary case:
the first time a part of the version reaches two digits.
The project does the job properly, and the tests are most of the project. Make a folder and a module:
mkdir versions
cd versions
go mod init versions
The code goes in versions.go. Compare returns -1 if the first version is older,
1 if it’s newer, and 0 if they’re the same. It splits each version on the dots,
turns each part into a number, and compares the numbers in order, so “1.2” and
“1.2.0” count as the same version:
package versions
import (
"fmt"
"strconv"
"strings"
)
func Compare(a, b string) (int, error) {
as, err := parts(a)
if err != nil {
return 0, err
}
bs, err := parts(b)
if err != nil {
return 0, err
}
for i := 0; i < max(len(as), len(bs)); i++ {
x, y := at(as, i), at(bs, i)
if x < y {
return -1, nil
}
if x > y {
return 1, nil
}
}
return 0, nil
}
func parts(version string) ([]int, error) {
var numbers []int
for _, field := range strings.Split(version, ".") {
n, err := strconv.Atoi(field)
if err != nil || n < 0 {
return nil, fmt.Errorf("%q is not a version number", version)
}
numbers = append(numbers, n)
}
return numbers, nil
}
func at(numbers []int, i int) int {
if i < len(numbers) {
return numbers[i]
}
return 0
}
Compare returns two values: the answer, and an error that is nil when nothing
went wrong. That’s Go’s way of reporting a failure as an ordinary value instead of
crashing (the Rust piece explains errors as values in full). It matters
here because something like "1.x" isn’t a version at all, and the only sensible
answer to “is 1.x newer than 1.0?” is “that isn’t a version”. strconv.Atoi
turns text into an integer and reports an error when it can’t.
The tests go in versions_test.go:
package versions
import "testing"
func TestCompare(t *testing.T) {
cases := []struct {
a, b string
want int
}{
{"1.2.0", "1.1.0", 1},
{"1.1.0", "1.2.0", -1},
{"1.2.0", "1.2.0", 0},
{"2.0.0", "1.9.9", 1},
{"1.10.0", "1.9.0", 1},
{"1.2", "1.2.0", 0},
{"1.2.1", "1.2", 1},
{"0.9", "0.10", -1},
}
for _, c := range cases {
got, err := Compare(c.a, c.b)
if err != nil {
t.Errorf("Compare(%q, %q) gave an error: %v", c.a, c.b, err)
continue
}
if got != c.want {
t.Errorf("Compare(%q, %q) = %d, want %d", c.a, c.b, got, c.want)
}
}
}
func TestCompareRejectsNonsense(t *testing.T) {
for _, bad := range []string{"", "1..2", "1.x", "v1.2", "1.-2"} {
if _, err := Compare(bad, "1.0"); err == nil {
t.Errorf("Compare(%q, \"1.0\") gave no error", bad)
}
}
}
Read the table before you run it, row by row, because each row is there for a
reason. The first three are the plain middle: newer, older, equal. Then the edges:
a change in the first part that outweighs bigger numbers later, the two-digit part
that broke the hurried version, versions of different lengths in both directions,
and the same two-digit trap one place over. The second test covers the other kind
of edge, input that should be refused: nothing at all, an empty part, letters, a
leading v, a negative number.
Run it:
$ go test -v
=== RUN TestCompare
--- PASS: TestCompare (0.00s)
=== RUN TestCompareRejectsNonsense
--- PASS: TestCompareRejectsNonsense (0.00s)
PASS
ok versions 0.002s
Green. Don’t trust it yet. Break something on purpose: in at, change return 0
to return 1, and run go test again. The rows comparing versions of different
lengths go red, and nothing else does. Put it back. Now try changing x < y to
x <= y and predict, before you run it, which rows will catch that. If you guessed
right, you understand the table. If you didn’t, the failures will show you
something about the code you hadn’t noticed.
Then ask Go how much of the code the tests touched:
$ go test -cover
PASS
coverage: 95.7% of statements
ok versions 0.003s
Coverage is the share of the code’s statements that ran at least once during the
tests. It’s a useful question with a misleading number. The missing few percent
here is a real gap: no test passes a bad version as the second argument, so that
return never runs. But 100% wouldn’t mean the code is right. It would mean every
line ran, not that every line was checked. Delete the if got != c.want check
from TestCompare and change got to _ in the line above it, so that it calls
Compare on every row and never looks at the answer, and coverage still says 95.7%. Use coverage to find code no test reaches, and use
your own judgment, edge by edge, for the rest.
What’s left out, and next
This piece left a lot out, so that one idea could stand clearly. Go’s
testing package does much more: subtests, which give each row of a table its own
name with t.Run so you can run one with go test -run; benchmarks, which
measure how fast code runs; fuzzing, where Go invents inputs for you and hunts for
ones that break your code; and examples, tests that double as documentation.
There are also whole schools of thought about testing that this piece skipped:
mocks and fakes that stand in for databases and networks, the different sizes of
test from a single function up to a whole running system, and test-driven
development, which turns “red first” into a way of designing code. Each makes more sense
once the basic habit is yours.
When a test fails and you can’t see why, the next skill is finding out what the code is really doing, which is the subject of the Debugging piece. For Go itself, its own piece is about Go and the way it runs many things at once.
To go further with Go’s tools, the Go team’s tutorial has a short
step on adding a test, and the Go wiki has
a page on table-driven tests with more
patterns. The full reference is go help test, go help testflag and
go doc testing, all already on your disk.
The hint
Compare has a bug waiting for you. Real versions are sometimes pre-releases,
like 1.0.0-beta, and a beta comes before the release it leads up to. Don’t fix
the code. First add the row that says so to the table:
{"1.0.0-beta", "1.0.0", -1},
Before you run go test, guess what it will say. Then run it and read the failure.
Is it the failure you expected? What does it tell you about how Compare sees that
version? Only then change the code, and watch that row go green with every other
row still green beside it.
Write the test before fixing the bug. It’s the one habit from this piece that travels to every language you’ll ever use.
Related
- Rust, for errors as values, which
Compareuses to refuse bad input. - Go, the language used here, through its own concept: message passing.
- Debugging, for when a test fails and you can’t see why.
Tested with Go 1.27.4, November 2026.