← 返回课程: Go from scratch

Table-driven tests and week 6 review

视频即将上线

In the previous lesson you wrote one test per case. It works, but when a function has ten interesting cases the file fills with repeated code. The Go community solved this with a pattern so widespread that almost all the standard library code uses it: table-driven tests. The idea is to separate data from logic: a table with the cases and a single loop that runs them all. Adding a new case comes down to writing one more line, and the tests stay easy to read.

The pattern

First you define a slice of anonymous structs, each with a descriptive name, the inputs and the expected result. Then you walk the table and, for each row, launch a subtest with t.Run(tc.name, ...). This way the output of go test -v shows the name of each case, and you can run just one with -run TestIsLeap/century. Always include edge cases: empty values, zero, negatives, the largest and smallest possible value, and error cases. That is where most bugs live.

go
// file: leap/leap.go
package leap

// IsLeap reports whether the given year is a leap year.
func IsLeap(year int) bool {
	return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}

// file: leap/leap_test.go
package leap

import "testing"

func TestIsLeap(t *testing.T) {
	tests := []struct {
		name string
		year int
		want bool
	}{
		{"regular leap", 2024, true},
		{"regular non leap", 2023, false},
		{"century", 1900, false},
		{"four hundred", 2000, true},
		{"zero", 0, true},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			if got := IsLeap(tc.year); got != tc.want {
				t.Errorf("IsLeap(%d) = %v; want %v", tc.year, got, tc.want)
			}
		})
	}
}

Tables with errors

When the function returns an error, add to the table a wantErr column of type bool, or better, the expected error to compare with errors.Is. In the test you first check the error and, only if it matches what is expected, compare the value. A good practice is to also test failure paths, not just the happy path: if a function promises to return ErrNotFound, write a test that demands it. Since Go 1.22 the loop variable is new on each iteration, so you can capture tc inside the t.Run closure without copying it by hand.

go
package parse

import (
	"errors"
	"strconv"
	"testing"
)

var ErrEmpty = errors.New("empty input")

func ParsePositive(s string) (int, error) {
	if s == "" {
		return 0, ErrEmpty
	}
	n, err := strconv.Atoi(s)
	if err != nil {
		return 0, err
	}
	if n <= 0 {
		return 0, errors.New("not positive")
	}
	return n, nil
}

func TestParsePositive(t *testing.T) {
	tests := []struct {
		name    string
		input   string
		want    int
		wantErr bool
	}{
		{"ok", "42", 42, false},
		{"empty", "", 0, true},
		{"letters", "abc", 0, true},
		{"zero", "0", 0, true},
		{"negative", "-5", 0, true},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			got, err := ParsePositive(tc.input)
			if (err != nil) != tc.wantErr {
				t.Fatalf("error = %v; wantErr %v", err, tc.wantErr)
			}
			if got != tc.want {
				t.Errorf("got %d; want %d", got, tc.want)
			}
		})
	}
}

Week 6 review

This week you learned to create a module with go mod, to organize code into packages with uppercase exporting, the cmd and internal structure, and to write tests with go test, subtests, helpers and coverage. You have also seen the table-driven test pattern, the standard way to cover many cases with little code. In week 7 you will enter the most emblematic part of Go: concurrency with goroutines and channels.

检验所学

第 1 / 7

What must the test file for calc.go be called?

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →