Go Playbook

Course › Week 2 · Methods, interfaces, errors, tests › Day 5 · lesson 12 of 42 · 10 min reading + 75–90 min practice

Tests with go test

A test is a function in a _test.go file, and a table of cases covers the edges in a few lines.

go testtesting.Ttable testst.Runcoverage

On this page
  1. The package under test
  2. A first test
  3. Table tests
  4. Coverage
  5. Coming from PHP
  6. Practice
  7. Remember

Go’s test runner is built into the go command, and a test is an ordinary function. No PHPUnit to install, no base class, no assertion library: a test compares values with if and reports what is wrong.

Today: a first test, what a failure looks like, table tests (Go’s data providers), subtests, testing that something fails, and coverage. All of it on one small pricing package.

The package under test

go mod init pricing, then this file. It is the pricing function from the packages lesson, now with a rule worth testing: 10% off the nights from 7 nights on, and an error for a stay with no nights.

pricing/pricing.gonew file
// Package pricing computes what a stay costs.
package pricing

import "fmt"

// cleaningFeeCents is added once to every stay.
const cleaningFeeCents = 4500

// TotalCents is the price of a stay: the nights, plus the cleaning fee. Stays of 7 nights or more
// get 10% off the nights.
func TotalCents(nights, nightlyCents int) (int, error) {
	if nights < 1 {
		return 0, fmt.Errorf("nights must be at least 1, got %d", nights)
	}
	stay := nights * nightlyCents
	if nights >= 7 {
		stay = stay * 90 / 100
	}
	return stay + cleaningFeeCents, nil
}

A first test

1. A test is a function in a _test.go file

Tests live next to the code, in a file whose name ends in _test.go, in the same package. A test function starts with Test, takes a *testing.T, and returns nothing.

pricing/pricing_test.gonew file
package pricing

import "testing"

func TestTotalCents(t *testing.T) {
	got, err := TotalCents(3, 12950)
	if err != nil {
		t.Fatalf("TotalCents(3, 12950) returned an error: %v", err)
	}
	want := 3*12950 + 4500
	if got != want {
		t.Errorf("TotalCents(3, 12950) = %d, want %d", got, want)
	}
}
$ go test
PASS
ok  	pricing	0.002s

go test compiles the package with its test files, runs every Test… function, and prints PASS, then ok with the package name and the time taken. (go test ./... prints only the ok line, one per package.) _test.go files are never part of your built program.

t.Errorf reports a failure and lets the test continue; t.Fatalf reports and stops this test at once. Use Fatalf when there is no point going on: here, without a result, comparing it means nothing.

The message style is Go’s convention: what was called, what it returned, what was wanted. TotalCents(3, 12950) = 38850, want 43350 tells you everything without opening the test.

2. A failing test

Change >= 7 to > 7 in pricing.go, the classic off-by-one, and run a test for 7 nights:

pricing/pricing_test.gochanged since the version above: +6 −7
package pricing import "testing" func TestTotalCents(t *testing.T) {	got, err := TotalCents(3, 12950)func TestSevenNightsGetTheDiscount(t *testing.T) {	got, err := TotalCents(7, 10000)	if err != nil {		t.Fatalf("TotalCents(3, 12950) returned an error: %v", err)	}	want := 3*12950 + 4500	if got != want {		t.Errorf("TotalCents(3, 12950) = %d, want %d", got, want)		t.Fatalf("TotalCents(7, 10000) returned an error: %v", err)	}	if want := 63000 + 4500; got != want {		t.Errorf("TotalCents(7, 10000) = %d, want %d", got, want)	}}
$ go test
--- FAIL: TestSevenNightsGetTheDiscount (0.00s)
    pricing_test.go:11: TotalCents(7, 10000) = 74500, want 67500
FAIL
exit status 1
FAIL	pricing	0.002s

--- FAIL names the test, then the file and line of the t.Errorf and its message: 7 nights cost 74500 instead of 67500, the discount is missing. go test exits with code 1, so a CI pipeline stops. Put >= 7 back before you go on.

Table tests

3. A table of cases, each a subtest

Most Go tests are table tests: a slice of cases, each a small struct with its inputs and the expected result, and one loop that checks them all. Adding a case is one line.

t.Run(name, func(t *testing.T) { … }) runs each case as a subtest with its own name, so a failure says which case failed, and you can run one case alone.

pricing/pricing_test.gochanged since the version above: +33 −9
package pricing import "testing" func TestSevenNightsGetTheDiscount(t *testing.T) {	got, err := TotalCents(7, 10000)	if err != nil {		t.Fatalf("TotalCents(7, 10000) returned an error: %v", err)	}	if want := 63000 + 4500; got != want {		t.Errorf("TotalCents(7, 10000) = %d, want %d", got, want)	}}func TestTotalCents(t *testing.T) {	tests := []struct {		name         string		nights       int		nightlyCents int		want         int	}{		{name: "one night", nights: 1, nightlyCents: 12950, want: 12950 + 4500},		{name: "six nights, no discount", nights: 6, nightlyCents: 10000, want: 60000 + 4500},		{name: "seven nights, 10% off", nights: 7, nightlyCents: 10000, want: 63000 + 4500},		{name: "free stay still pays cleaning", nights: 2, nightlyCents: 0, want: 4500},	} 	for _, tt := range tests {		t.Run(tt.name, func(t *testing.T) {			got, err := TotalCents(tt.nights, tt.nightlyCents)			if err != nil {				t.Fatalf("unexpected error: %v", err)			}			if got != tt.want {				t.Errorf("TotalCents(%d, %d) = %d, want %d", tt.nights, tt.nightlyCents, got, tt.want)			}		})	}} func TestTotalCentsRejectsNoNights(t *testing.T) {	for _, nights := range []int{0, -1} {		if _, err := TotalCents(nights, 12950); err == nil {			t.Errorf("TotalCents(%d, 12950) returned no error", nights)		}	}}
$ go test -v
=== RUN   TestTotalCents
=== RUN   TestTotalCents/one_night
=== RUN   TestTotalCents/six_nights,_no_discount
=== RUN   TestTotalCents/seven_nights,_10%_off
=== RUN   TestTotalCents/free_stay_still_pays_cleaning
--- PASS: TestTotalCents (0.00s)
    --- PASS: TestTotalCents/one_night (0.00s)
    --- PASS: TestTotalCents/six_nights,_no_discount (0.00s)
    --- PASS: TestTotalCents/seven_nights,_10%_off (0.00s)
    --- PASS: TestTotalCents/free_stay_still_pays_cleaning (0.00s)
=== RUN   TestTotalCentsRejectsNoNights
--- PASS: TestTotalCentsRejectsNoNights (0.00s)
PASS
ok  	pricing	0.003s

[]struct{ … }{ … } is a slice of a struct type with no name, declared on the spot: the table needs no type of its own. func(t *testing.T) { … } is a function without a name, written where it is passed; Week 3 explains these properly. tt is the usual name for the current case.

-v prints every test and subtest as it runs, with PASS or FAIL. Without -v, a passing run prints only the summary. Subtest names have their spaces turned into _, and go test -run "TestTotalCents/seven_nights" runs just that case.

TestTotalCentsRejectsNoNights tests the failure path. A function that returns an error has two behaviours, and both need a test; the edge cases (0, a negative number) are where bugs live.

Coverage

4. go test -cover

-cover reports the share of statements your tests ran.

$ go test -cover
PASS
coverage: 100.0% of statements
ok  	pricing	0.003s

Every statement of TotalCents ran at least once: the error, the discount and the normal path. go test -coverprofile=cover.out followed by go tool cover -html=cover.out opens the code in a browser with each line coloured by whether a test ran it.

Coverage shows what was never tested; it does not show what was tested well. A test that calls a function without checking the result covers every line and proves nothing.

5. The commands you will use

CommandWhat it does
go test ./...Every package of the module, quietly: ok or the failures
go test -v ./...Every test by name, with its result
go test -run TestTotalCents ./...Only tests whose name matches the pattern
go test -cover ./...With coverage per package
go test -count=1 ./...Run again even if nothing changed; without it, a package whose code did not change prints (cached)

Coming from PHP

tests/Unit/PricingTest.php
<?php
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

final class PricingTest extends TestCase
{
    #[DataProvider('stays')]
    public function test_total(int $nights, int $nightly, int $want): void
    {
        $this->assertSame($want, Pricing::totalCents($nights, $nightly));
    }

    public static function stays(): array
    {
        return [
            'seven nights, 10% off' => [7, 10000, 63000 + 4500],
        ];
    }
}

A data provider and a table test are the same idea. The Go version keeps the cases next to the loop that checks them, with named fields instead of positions, and needs no framework.

The honest difference: Go has no assertSame and no mocking library in the standard library, on purpose. You write the comparison, and you replace dependencies with small interfaces (the interfaces lesson) instead of mocks. It is more typing, and the failure messages are exactly the ones you wrote.

PracticeLearn Go with Tests: Hello, World to Arrays and slices

From here on, Learn Go with Tests is the main practice: it teaches by writing the test first. Do Hello, World, Integers, Iteration and Arrays and slices. They repeat Week 1 the test-first way, which is the point.

Exercise: test the level parser

Take Parse from the exercise of the packages lesson and write a table test for it: every known name, a lowercase name, an empty string and an unknown name. Then run it with -cover: anything below 100% points at a path you did not test.

Remember

  • Tests are Test… functions in _test.go files next to the code; go test ./... runs them all.
  • Write table tests with t.Run, and test the failure paths as carefully as the happy one.
  • Messages say what was called, what it returned, and what was wanted.

Tomorrow is the build day: logstat v2, with flags, a parser in its own package, wrapped errors and tests.