← 講座に戻る: Go from scratch

Testing with go test

動画は近日公開

A program that is not tested is a program you only hope works. Automated tests are small programs that run your code with known inputs and check that the result is the expected one. They give you confidence to change things without breaking them and document the desired behavior. The best thing about Go is that testing is built in: you do not need to install any framework, the testing package of the standard library and the go test command are enough.

Your first test

The rules are few. The test file must end in _test.go and be in the same folder as the code it tests, normally with the same package name. Each test is a function that starts with Test followed by a name in uppercase, and receives a single parameter, t *testing.T. Inside you call the code and, if the result is not the expected one, you report it with t.Errorf, which records the failure but keeps running, or with t.Fatalf, which stops that test. If the function ends without reporting failures, the test passes. A good error message states what was obtained and what was expected.

go
// file: calc/calc.go
package calc

import "errors"

func Add(a, b int) int { return a + b }

func Divide(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("division by zero")
	}
	return a / b, nil
}

// file: calc/calc_test.go
package calc

import "testing"

func TestAdd(t *testing.T) {
	got := Add(2, 3)
	want := 5
	if got != want {
		t.Errorf("Add(2, 3) = %d; want %d", got, want)
	}
}

func TestDivideByZero(t *testing.T) {
	_, err := Divide(10, 0)
	if err == nil {
		t.Fatal("expected an error, got nil")
	}
}

Note: the two blocks of the previous example are two different files; the comments with file: indicate where each goes. To run the tests you use go test. Without arguments it tests the package of the current folder; with ./... it tests all packages of the module. The -v flag shows the name of each test and its result, and -run lets you choose tests by regular expression. If the code has a bug, go test prints FAIL, the file, the line and your message.

bash
go test                 # current package
go test ./...           # all packages in the module
go test -v -run Add     # verbose, only tests matching "Add"
go test -cover          # shows the percentage of code covered
go test -race ./...     # detects data races (useful in week 7)

Helpers, subtests and coverage

When several tests repeat a check, extract it into a helper function and start it with t.Helper(): that way, if it fails, the error points to the test's line and not to the helper's. With t.Run(name, func(t *testing.T){...}) you create subtests, which appear separately in the output and can be run individually. The -cover flag measures what percentage of lines your tests run; a high number does not guarantee they are good, but a low one shows there are unwatched areas. Tests that sometimes fail (flaky) are worse than having no tests: fix them or delete them.

go
package calc

import "testing"

func assertEqual(t *testing.T, got, want int) {
	t.Helper() // failure is reported at the caller's line
	if got != want {
		t.Errorf("got %d; want %d", got, want)
	}
}

func TestAddSubtests(t *testing.T) {
	t.Run("positives", func(t *testing.T) {
		assertEqual(t, Add(1, 2), 3)
	})
	t.Run("negatives", func(t *testing.T) {
		assertEqual(t, Add(-1, -2), -3)
	})
	t.Run("zero", func(t *testing.T) {
		assertEqual(t, Add(0, 0), 0)
	})
}
  • *_test.go files; TestXxx(t *testing.T) functions.
  • t.Errorf continues; t.Fatalf stops the test.
  • go test ./... tests the whole module.
  • t.Run creates subtests; t.Helper() improves messages.
  • Write messages with got and want.

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →