These are the notes for Go episode 40. Raju's shop gives 10% off on orders of Rs 500 or more. After every change he prints a few bills in main and looks at them, and one day a bug slips through: an order of exactly 500 is charged 500 instead of 450, and nobody notices for a week. So you invent automated tests: an answer key for your code that the computer checks for you. You write your first test with the testing package, run it with go test, use -v and -run, learn when to use t.Error and when t.Fatal, replace copy-pasted tests with table-driven tests and subtests, make helpers report the right line with t.Helper, keep tests clean with t.TempDir, t.Setenv and t.Cleanup, and find untested code with coverage.
All outputs and errors here are from real runs (Go 1.24.7, linux/amd64). Timings like 0.002s change on every run.
How the SyntaxPilot compiler runs tests. A normal program is one file run with go run main.go. A test needs a package with at least two files, so in the compiler a program whose first lines are // $ go test ... is treated as a package: each line // ---- name.go ---- starts a new file, and the commands at the top run in that folder, in order (a go.mod for module shop is added for you). On your own computer, make a folder, run go mod init shop, create the files shown below, and type the same commands.
Facts and sources
go doc testing(Go 1.24.7): "Package testing provides support for automated testing of Go packages. It is intended to be used in concert with the "go test" command, which automates execution of any function of the formfunc TestXxx(*testing.T)where Xxx does not start with a lowercase letter." and "To write a new test suite, create a file that contains the TestXxx functions as described here, and give that file a name ending in "_test.go". The file will be excluded from regular package builds but will be included when the "go test" command is run."go doc testingon failing: "Fail marks the function as having failed but continues execution." "FailNow marks the function as having failed and stops its execution".ErrorisLog+Fail;FatalisLog+FailNow.go doc testing.T.Helper: "Helper marks the calling function as a test helper function. When printing file and line information, that function will be skipped."go doc testing.T.TempDir: "TempDir returns a temporary directory for the test to use. The directory is automatically removed when the test and all its subtests complete."go doc testing.T.Setenv: "Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable to its original value after the test. Because Setenv affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors."go help testflag:-run regexp"Run only those tests, examples, and fuzz tests matching the regular expression";-cover"Enable coverage analysis";-coverprofile cover.out"Write a coverage profile to the file after all tests have passed";-v"Verbose output: log all tests as they are run."go help test: "As part of building a test binary, go test runs go vet on the package and its test source files to identify significant problems." (That is where the "malformed name" error comes from.)
The problem: checking by eye
main.go, run with go run main.go:
package main
import "fmt"
// orders of Rs 500 or more get 10% off
func Bill(amount int) int {
if amount > 500 {
return amount * 90 / 100
}
return amount
}
func main() {
// Raju checks by eye after every change
fmt.Println(Bill(300))
fmt.Println(Bill(500))
fmt.Println(Bill(800))
}
Output (real run):
300
500
720
300, 500, 720 looks fine. But an order of exactly 500 should get the discount and cost 450: the code says amount > 500 where it should say amount >= 500. Raju saw this output and missed it.
Why checking by eye fails: a human compares numbers by eye, gets tired, and only checks when they remember to. We need a check that knows the right answer, compares it for us, and runs every time in a second. That is an automated test.
Your first test (the answer key)
| In an exam hall | In Go |
|---|---|
| The answer key: the right answer for every question | a test function: func TestBill(t *testing.T) |
| The OMR machine checks every sheet, fast, never tired | the go test command runs every test, every time |
| "Q7: wrote B, answer is C" | t.Errorf: Bill(500) = 500, want 450 |
The rules:
- Tests live in a file whose name ends in
_test.go(shop_test.go), in the same folder as the code (shop.go).go buildignores these files;go testcompiles them. - The test file imports the
testingpackage (the standard library package for tests). - A test function is named
Testfollowed by a capital letter, a digit, or nothing (TestBill,Test2,Test), and takes one parametert *testing.T.testing.Tis the test's handle: you report problems through it, andgo testgives every test its ownt. - You compute what you got, compare it with what you want (the right answer), and report a mismatch with
t.Errorf(formatted likefmt.Printf). The Go convention for messages isFunc(args) = got, want want.
shop.go:
package shop
// orders of Rs 500 or more get 10% off
func Bill(amount int) int {
if amount > 500 {
return amount * 90 / 100
}
return amount
}
shop_test.go:
package shop
import "testing"
func TestBill(t *testing.T) {
got := Bill(500)
if got != 450 {
t.Errorf("Bill(500) = %d, want 450", got)
}
}
Run in the package folder:
go test
Output (real run):
$ go test
--- FAIL: TestBill (0.00s)
shop_test.go:8: Bill(500) = 500, want 450
FAIL
exit status 1
FAIL shop 0.002s
go test found the bug Raju's eyes missed, and points at the exact file and line (shop_test.go:8). Now fix it (amount >= 500) and run again:
Output (real run):
$ go test
PASS
ok shop 0.001s
PASS and ok shop 0.005s: shop is the package that was tested, and the time is how long the tests took. A test that catches an old bug if it ever comes back is called a regression test. Run go test after every change.
go test -v and -run
-v(verbose) prints every test as it runs:=== RUN, then--- PASSor--- FAILwith its time.-run Patternruns only tests whose names match the regular expression (a text pattern;Smallmatches any name containing "Small",^TestBill$exactly one name).
shop.go:
package shop
func Bill(amount int) int {
if amount >= 500 {
return amount * 90 / 100
}
return amount
}
shop_test.go:
package shop
import "testing"
func TestBillBig(t *testing.T) {
if got := Bill(800); got != 720 {
t.Errorf("Bill(800) = %d, want 720", got)
}
}
func TestBillSmall(t *testing.T) {
if got := Bill(300); got != 300 {
t.Errorf("Bill(300) = %d, want 300", got)
}
}
Run in the package folder:
go test -v
go test -v -run Small
Output (real run):
$ go test -v
=== RUN TestBillBig
--- PASS: TestBillBig (0.00s)
=== RUN TestBillSmall
--- PASS: TestBillSmall (0.00s)
PASS
ok shop 0.001s
$ go test -v -run Small
=== RUN TestBillSmall
--- PASS: TestBillSmall (0.00s)
PASS
ok shop 0.002s
A badly named test
shop.go:
package shop
func Bill(amount int) int {
if amount >= 500 {
return amount * 90 / 100
}
return amount
}
shop_test.go:
package shop
import "testing"
func Testbill(t *testing.T) { // lowercase b
if got := Bill(500); got != 1 {
t.Errorf("Bill(500) = %d, want 1", got)
}
}
Run in the package folder:
go test
Output (real run):
$ go test
FAIL shop [build failed]
# shop
# [shop]
./shop_test.go:5:6: Testbill has malformed name: first letter after 'Test' must not be lowercase
go test runs go vet (Go's checker for suspicious code) before testing. Testbill would never run as a test (the letter after Test is lowercase), so vet stops the build.
And if the file name doesn't end in _test.go, go test finds nothing:
shop.go:
package shop
func Bill(a int) int { return a }
shop_check.go:
package shop
import "testing"
func TestBill(t *testing.T) {}
Run in the package folder:
go test
Output (real run):
$ go test
? shop [no test files]
t.Error vs t.Fatal (the car inspector)
| At a car inspection | In a Go test |
|---|---|
| A scratch on the door: note it, keep checking | t.Error / t.Errorf: mark the test failed, continue |
| No engine at all: stop, nothing else makes sense | t.Fatal / t.Fatalf: mark the test failed, stop this test |
shop.go:
package shop
import "errors"
type Order struct{ ID int; Item string }
var orders = map[int]*Order{41: {41, "chai"}}
func Find(id int) (*Order, error) {
o, ok := orders[id]
if !ok {
return nil, errors.New("order not found")
}
return o, nil
}
shop_test.go:
package shop
import "testing"
func TestFind(t *testing.T) {
o, err := Find(42)
if err != nil {
t.Error("Find(42):", err) // marks failed, keeps going
}
if o.Item != "samosa" {
t.Errorf("item = %q, want samosa", o.Item)
}
}
Run in the package folder:
go test
Output (real run):
$ go test
--- FAIL: TestFind (0.00s)
shop_test.go:8: Find(42): order not found
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x51fb23]
goroutine 18 [running]:
testing.tRunner.func1.2({0x550000, 0x6a0770})
/usr/local/go1.24.7/src/testing/testing.go:1734 +0x21c
testing.tRunner.func1()
/usr/local/go1.24.7/src/testing/testing.go:1737 +0x35e
panic({0x550000?, 0x6a0770?})
/usr/local/go1.24.7/src/runtime/panic.go:792 +0x132
shop.TestFind(0xc000124380)
shop_test.go:10 +0xc3
testing.tRunner(0xc000124380, 0x584780)
/usr/local/go1.24.7/src/testing/testing.go:1792 +0xf4
created by testing.(*T).Run in goroutine 1
/usr/local/go1.24.7/src/testing/testing.go:1851 +0x413
exit status 2
FAIL shop 0.005s
t.Error reported "order not found" but the test kept going, so o.Item was read through a nil pointer (episode 11): a panic. Use t.Fatal when the rest of the test depends on this step:
Output (real run):
$ go test
--- FAIL: TestFind (0.00s)
shop_test.go:8: Find(42): order not found
FAIL
exit status 1
FAIL shop 0.002s
A clean failure. t.Fatal stops only the current test (it calls runtime.Goexit); other tests still run. Note: t.Fatal must be called from the goroutine running the test, not from a goroutine the test started.
| Use | When |
|---|---|
t.Error, t.Errorf |
independent checks: you want to see every failure in one run |
t.Fatal, t.Fatalf |
the next lines need this result (an error from setup, a nil pointer) |
t.Log, t.Logf |
extra information, printed with -v or when the test fails |
Table-driven tests (the mark sheet)
Copy-pasting a test for each input works, but only the data changes between copies:
shop.go:
package shop
func Bill(amount int) int {
if amount >= 500 {
return amount * 90 / 100
}
return amount
}
shop_test.go:
package shop
import "testing"
func TestBill300(t *testing.T) {
if got := Bill(300); got != 300 {
t.Errorf("Bill(300) = %d, want 300", got)
}
}
func TestBill500(t *testing.T) {
if got := Bill(500); got != 450 {
t.Errorf("Bill(500) = %d, want 450", got)
}
}
func TestBill800(t *testing.T) {
if got := Bill(800); got != 720 {
t.Errorf("Bill(800) = %d, want 720", got)
}
}
// ...and 20 more copies
Run in the package folder:
go test
Output (real run):
$ go test
PASS
ok shop 0.060s
| A teacher's mark sheet | In a Go test |
|---|---|
| One row per student: name, marks, grade | a slice of test cases: []struct{ amount, want int } |
| The same rule for every row | one for loop over the cases |
Put the cases in a table (a slice of anonymous structs, episode 19) and loop over it: a table-driven test, the most common test style in Go. tc is the usual name for one test case.
shop.go:
package shop
func Bill(amount int) int {
if amount >= 500 {
return amount * 90 / 100
}
return amount
}
shop_test.go:
package shop
import "testing"
func TestBill(t *testing.T) {
tests := []struct {
amount, want int
}{
{300, 300},
{500, 450},
{800, 720},
{0, 0},
{499, 499},
{1000, 910}, // a wrong want, on purpose
}
for _, tc := range tests {
if got := Bill(tc.amount); got != tc.want {
t.Errorf("Bill(%d) = %d, want %d", tc.amount, got, tc.want)
}
}
}
Run in the package folder:
go test
Output (real run):
$ go test
--- FAIL: TestBill (0.00s)
shop_test.go:18: Bill(1000) = 900, want 910
FAIL
exit status 1
FAIL shop 0.002s
Here the want was wrong (10% off 1000 is 900), so the test had the bug. Always check your answer key too. Adding a case is now one line.
Subtests with t.Run
t.Run(name, func(t *testing.T) {...}) runs a subtest: a test inside a test, with its own name, its own t and its own PASS/FAIL. With -run, a slash selects subtests: -run TestBill/big.
shop.go:
package shop
func Bill(amount int) int {
if amount >= 500 {
return amount * 90 / 100
}
return amount
}
shop_test.go:
package shop
import "testing"
func TestBill(t *testing.T) {
tests := []struct {
name string
amount, want int
}{
{"small", 300, 300},
{"edge", 500, 450},
{"big", 800, 720},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := Bill(tc.amount); got != tc.want {
t.Errorf("got %d, want %d", got, tc.want)
}
})
}
}
Run in the package folder:
go test -v
go test -v -run TestBill/big
Output (real run):
$ go test -v
=== RUN TestBill
=== RUN TestBill/small
=== RUN TestBill/edge
=== RUN TestBill/big
--- PASS: TestBill (0.00s)
--- PASS: TestBill/small (0.00s)
--- PASS: TestBill/edge (0.00s)
--- PASS: TestBill/big (0.00s)
PASS
ok shop 0.125s
$ go test -v -run TestBill/big
=== RUN TestBill
=== RUN TestBill/big
--- PASS: TestBill (0.00s)
--- PASS: TestBill/big (0.00s)
PASS
ok shop 0.002s
- Spaces in subtest names become underscores (
"one chai"→TestPrice/one_chai). t.Fatalinside a subtest stops only that subtest; the other rows still run.- Since Go 1.22 every loop iteration has its own
tcvariable (episode 8), so each subtest sees its own row. In older Go you had to writetc := tcinside the loop.
t.Helper
A helper function that checks something is handy, but failures are reported at the line inside the helper:
shop.go:
package shop
func Bill(amount int) int {
if amount >= 500 {
return amount * 90 / 100
}
return amount
}
shop_test.go:
package shop
import "testing"
func check(t *testing.T, amount, want int) {
if got := Bill(amount); got != want {
t.Errorf("Bill(%d) = %d, want %d", amount, got, want)
}
}
func TestBill(t *testing.T) {
check(t, 300, 300)
check(t, 500, 450)
check(t, 800, 700) // wrong on purpose: which line?
}
Run in the package folder:
go test
Output (real run):
$ go test
--- FAIL: TestBill (0.00s)
shop_test.go:7: Bill(800) = 720, want 700
FAIL
exit status 1
FAIL shop 0.042s
Line 7 is the t.Errorf inside check: the same for every call. Add t.Helper() as the first line of the helper:
shop.go:
package shop
func Bill(amount int) int {
if amount >= 500 {
return amount * 90 / 100
}
return amount
}
shop_test.go:
package shop
import "testing"
func check(t *testing.T, amount, want int) {
t.Helper() // report the caller's line
if got := Bill(amount); got != want {
t.Errorf("Bill(%d) = %d, want %d", amount, got, want)
}
}
func TestBill(t *testing.T) {
check(t, 300, 300)
check(t, 500, 450)
check(t, 800, 700) // wrong on purpose: which line?
}
Run in the package folder:
go test
Output (real run):
$ go test
--- FAIL: TestBill (0.00s)
shop_test.go:15: Bill(800) = 720, want 700
FAIL
exit status 1
FAIL shop 0.002s
Line 15 is the call check(t, 800, 700), exactly where to look.
t.TempDir, t.Setenv, t.Cleanup and t.Log
An environment variable is a named setting the operating system passes to every program (SHOP_CITY=Pune), read with os.Getenv. Tests must not litter the disk or change the machine's settings:
| Method | What it does |
|---|---|
t.TempDir() |
returns a fresh empty folder, deleted automatically after the test |
t.Setenv(key, value) |
sets an environment variable for this test only, restores it afterwards (not allowed in parallel tests) |
t.Cleanup(func()) |
registers a function to run when the test (and its subtests) finish; like defer (episode 10) but for the whole test; last registered runs first |
t.Log, t.Logf |
print a message attached to the test; shown with -v or on failure |
shop.go:
package shop
import (
"os"
"path/filepath"
)
// SaveMenu writes the menu into dir and returns the file path.
func SaveMenu(dir, menu string) (string, error) {
city := os.Getenv("SHOP_CITY") // e.g. Pune
path := filepath.Join(dir, city+"_menu.txt")
return path, os.WriteFile(path, []byte(menu), 0o644)
}
shop_test.go:
package shop
import (
"os"
"testing"
)
func TestSaveMenu(t *testing.T) {
t.Setenv("SHOP_CITY", "Pune") // undone when the test ends
dir := t.TempDir() // a fresh folder, deleted after
t.Cleanup(func() { t.Log("cleanup: close the database") })
path, err := SaveMenu(dir, "chai 20\nsamosa 15")
if err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(path)
t.Logf("wrote %d bytes to %s", len(data), path[len(dir)+1:])
if string(data) != "chai 20\nsamosa 15" {
t.Errorf("menu = %q", data)
}
}
Run in the package folder:
go test -v
Output (real run):
$ go test -v
=== RUN TestSaveMenu
shop_test.go:18: wrote 17 bytes to Pune_menu.txt
shop_test.go:11: cleanup: close the database
--- PASS: TestSaveMenu (0.00s)
PASS
ok shop 0.003s
The cleanup message comes after the test body. The temp folder is already deleted.
Test coverage (the highlighter)
| Studying for an exam | In Go |
|---|---|
| Highlight what you studied; unmarked pages are the risk | test coverage: which lines the tests actually ran |
| "I covered 60% of the syllabus" is not 60% marks | coverage shows what ran, not that it was checked well |
A statement is one instruction in the code (an if, a return, an assignment). Coverage is the percentage of statements that ran during the tests.
shop.go:
package shop
func Bill(amount int) int {
if amount >= 500 {
return amount * 90 / 100
}
return amount
}
func Delivery(km int) int {
if km > 5 {
return 40
}
return 0
}
shop_test.go:
package shop
import "testing"
func TestBill(t *testing.T) {
if got := Bill(800); got != 720 {
t.Errorf("Bill(800) = %d, want 720", got)
}
}
Run in the package folder:
go test -cover
go test -coverprofile=c.out
go tool cover -func=c.out
Output (real run):
$ go test -cover
PASS
coverage: 33.3% of statements
ok shop 0.003s
$ go test -coverprofile=c.out
PASS
coverage: 33.3% of statements
ok shop 0.002s
$ go tool cover -func=c.out
shop/shop.go:3: Bill 66.7%
shop/shop.go:10: Delivery 0.0%
total: (statements) 33.3%
-coverprints the percentage.-coverprofile=c.outalso saves line-by-line data to the filec.out(a coverage profile).go tool cover -func=c.outprints coverage per function:Bill66.7% (the small-orderreturnnever ran),Delivery0%.go tool cover -html=c.outopens the code in your browser, covered lines green and uncovered red.
With tests for both branches of both functions:
shop.go:
package shop
func Bill(amount int) int {
if amount >= 500 {
return amount * 90 / 100
}
return amount
}
func Delivery(km int) int {
if km > 5 {
return 40
}
return 0
}
shop_test.go:
package shop
import "testing"
func TestBill(t *testing.T) {
for _, tc := range []struct{ amount, want int }{{300, 300}, {800, 720}} {
if got := Bill(tc.amount); got != tc.want {
t.Errorf("Bill(%d) = %d, want %d", tc.amount, got, tc.want)
}
}
}
func TestDelivery(t *testing.T) {
for _, tc := range []struct{ km, want int }{{3, 0}, {5, 0}, {6, 40}} {
if got := Delivery(tc.km); got != tc.want {
t.Errorf("Delivery(%d) = %d, want %d", tc.km, got, tc.want)
}
}
}
Run in the package folder:
go test -cover
Output (real run):
$ go test -cover
PASS
coverage: 100.0% of statements
ok shop 0.002s
100% coverage still doesn't prove the code is right: it only proves every line ran. Good tests check the edges (499, 500, 501) and the error cases.
Mini project: test a price calculator
Write Price(item string, qty int) (int, error) with a small menu (chai 20, samosa 15). Unknown items and quantities below 1 return errors. Test it with a table-driven test and named subtests, including the error cases, and reach 100% coverage.
Solution
price.go:
package shop
import (
"errors"
"fmt"
)
var menu = map[string]int{"chai": 20, "samosa": 15}
var ErrBadQty = errors.New("quantity must be at least 1")
// Price returns the cost of qty items, or an error.
func Price(item string, qty int) (int, error) {
if qty < 1 {
return 0, ErrBadQty
}
p, ok := menu[item]
if !ok {
return 0, fmt.Errorf("%q is not on the menu", item)
}
return p * qty, nil
}
price_test.go:
package shop
import "testing"
func TestPrice(t *testing.T) {
tests := []struct {
name string
item string
qty int
want int
wantErr bool
}{
{"one chai", "chai", 1, 20, false},
{"three chai", "chai", 3, 60, false},
{"two samosa", "samosa", 2, 30, false},
{"zero qty", "chai", 0, 0, true},
{"negative qty", "samosa", -1, 0, true},
{"unknown item", "pizza", 1, 0, true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := Price(tc.item, tc.qty)
if (err != nil) != tc.wantErr {
t.Fatalf("err = %v, wantErr %v", err, tc.wantErr)
}
if got != tc.want {
t.Errorf("got %d, want %d", got, tc.want)
}
})
}
}
Run in the package folder:
go test -v -cover
Output (real run):
$ go test -v -cover
=== RUN TestPrice
=== RUN TestPrice/one_chai
=== RUN TestPrice/three_chai
=== RUN TestPrice/two_samosa
=== RUN TestPrice/zero_qty
=== RUN TestPrice/negative_qty
=== RUN TestPrice/unknown_item
--- PASS: TestPrice (0.00s)
--- PASS: TestPrice/one_chai (0.00s)
--- PASS: TestPrice/three_chai (0.00s)
--- PASS: TestPrice/two_samosa (0.00s)
--- PASS: TestPrice/zero_qty (0.00s)
--- PASS: TestPrice/negative_qty (0.00s)
--- PASS: TestPrice/unknown_item (0.00s)
PASS
coverage: 100.0% of statements
ok shop 0.002s
wantErr bool is a common pattern: (err != nil) != tc.wantErr is true when we got an error we didn't expect, or didn't get one we did.
Common mistakes (and the real messages)
| Mistake | Real message / result | Why | Fix |
|---|---|---|---|
| checking output by eye | 500 printed, nobody noticed |
humans miss things | write a test |
func Testbill(t *testing.T) |
Testbill has malformed name: first letter after 'Test' must not be lowercase |
the TestXxx rule |
TestBill |
tests in shop_check.go |
? shop [no test files] |
not a _test.go file |
shop_test.go |
t.Error then using the nil result |
panic: runtime error: invalid memory address or nil pointer dereference |
Error keeps going |
t.Fatal |
a helper without t.Helper() |
failure points inside the helper | wrong line reported | t.Helper() first |
a wrong want in the table |
Bill(1000) = 900, want 910 |
the answer key is wrong | check expected values |
t.Setenv with t.Parallel |
panic: testing: test using t.Setenv or t.Chdir can not use t.Parallel |
env is process-wide | don't mix them |
Practice
- (Homework) Build and test the price calculator (solution above).
- (Homework) Reach 100% coverage on it with
go test -cover. - (Homework) Rerun just one subtest with
-run 'TestPrice/unknown_item'. - (Homework) Take a copy-pasted test and turn it into a table.
- Write a test for
Deliverythat checks 5 km (free) and 6 km (Rs 40): the edge.
Solution 5
See the DELIVERY program in the coverage section: the cases {5, 0} and {6, 40} test both sides of km > 5.
Quick quiz
1. What does this test report? (From the video.)
func TestX(t *testing.T) {
t.Error("first")
t.Fatal("second")
t.Error("third")
}
A. first and second · B. only first · C. all three · D. nothing, it passes
Answer
A. t.Error continues, t.Fatal reports and stops. Real run:
Output (real run):
$ go test
--- FAIL: TestX (0.00s)
shop_test.go:6: first
shop_test.go:7: second
FAIL
exit status 1
FAIL shop 0.004s
2. Which file name does go test pick up: shop_tests.go, shop_test.go, test_shop.go?
Answer
Only shop_test.go: the name must end in _test.go.
3. How do you run only the edge row of TestBill?
Answer
go test -run TestBill/edge (add -v to see it).
4. Coverage is 100%. Is the code correct?
Answer
Not necessarily: every line ran, but the checks might be weak or wrong.
Interview questions
- How do you write and run a unit test in Go? A
TestXxx(t *testing.T)function in a_test.gofile; rungo testin the package folder (orgo test ./...for all packages). t.Errorvst.Fatal? Both mark failure;Errorcontinues,Fatalstops the current test.- What is a table-driven test and why is it idiomatic? A slice of cases looped over with one check; less repetition, easy to add cases, clear failure messages.
- What are subtests good for? Named cases with separate results, running one case with
-run Test/name, per-caseFatal, and (next episode) parallel cases. - What does
t.Helperdo? Makes failures report the caller's line instead of the helper's. - How do you avoid tests leaving files or settings behind?
t.TempDir,t.Setenv,t.Cleanup. - What does coverage measure, and what doesn't it? Which statements ran; not whether the assertions were meaningful.
- Why does
go testsometimes fail before running any test? It runsgo vetfirst and compiles the test files; vet problems and compile errors stop it.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Automated test | code that checks other code against the right answer, run by a tool | TestBill |
| Unit test | a test of one small piece (a function) on its own | TestBill checks only Bill |
| Regression test | a test that catches an old bug coming back | the Bill(500) test |
testing package |
Go's standard library package for tests | import "testing" |
_test.go file |
a file only compiled by go test |
shop_test.go |
| Test function | func TestXxx(t *testing.T), run by go test |
func TestBill(t *testing.T) |
*testing.T |
the test's handle, used to report results | t.Errorf(...) |
| got / want | the actual result / the expected (right) result | Bill(500) = 500, want 450 |
go test |
builds and runs a package's tests | go test, go test ./... |
| PASS / FAIL / ok | test results; ok is the package summary line |
ok shop 0.002s |
go vet |
Go's checker for suspicious code, run by go test |
malformed test name |
-v |
verbose: print every test as it runs | go test -v |
-run |
run only tests matching a regular expression | go test -run Small |
| Regular expression | a text pattern for matching names | ^TestBill$ |
t.Error, t.Errorf |
report a failure, keep going | t.Errorf("got %d", x) |
t.Fatal, t.Fatalf |
report a failure, stop this test | t.Fatal(err) |
t.Log, t.Logf |
print a message for this test (shown with -v) |
t.Logf("wrote %d bytes", n) |
| Table-driven test | test cases in a slice, checked by one loop | tests := []struct{...}{...} |
Test case (tc) |
one input and its wanted answer | {500, 450} |
| Subtest | a named test inside a test | t.Run("edge", ...) |
t.Run |
starts a subtest | t.Run(tc.name, func(t *testing.T) {...}) |
| Test helper | a function that does checks for tests | check(t, 300, 300) |
t.Helper |
report failures at the caller's line | t.Helper() |
| Environment variable | a named setting the OS gives a program | SHOP_CITY=Pune |
t.Setenv |
set an environment variable for one test | t.Setenv("SHOP_CITY", "Pune") |
t.TempDir |
a temporary folder deleted after the test | dir := t.TempDir() |
t.Cleanup |
run a function when the test finishes | t.Cleanup(func() {...}) |
| Statement | one instruction in code | return amount |
| Test coverage | the share of statements the tests ran | coverage: 33.3% of statements |
-cover |
print coverage | go test -cover |
-coverprofile |
save coverage data to a file | go test -coverprofile=c.out |
| Coverage profile | the file with line-by-line coverage | c.out |
go tool cover |
reads a profile: -func per function, -html in a browser |
go tool cover -func=c.out |
Summary
- Checking output by eye misses bugs; an automated test knows the right answer and runs every time.
- Tests live in
_test.gofiles, in functionsTestXxx(t *testing.T);go testruns them (aftergo vet). -vlists tests,-runpicks them with a regular expression.t.Errorrecords and continues;t.Fatalrecords and stops the test.- Table-driven tests replace copy-paste;
t.Runmakes each row a named subtest (-run TestBill/big). t.Helperpoints failures at the caller;t.TempDir,t.Setenv,t.Cleanupkeep tests clean.- Coverage (
-cover,-coverprofile,go tool cover) shows which code never ran.
Next episode: Testing in depth: black-box tests, fakes, stubs and mocks, testdata and golden files, Example tests, TestMain, t.Parallel, build tags, -short, and test caching.