Go Test

Go Test #

Unit Test #

Run #

Run all unit tests #

$ go test ./...

Show detailed information

$ go test ./... -v

Disable test cache

$ go test ./... -count=1

Run a method of a unit test #

$ go test ./mypkg/ -run TestSample

Coverage #

Output coverage to a terminal

$ go test -cover ./...

Output the coverage profile to a file and view it in a browser

$ go test -coverprofile=cover.out ./...
$ go tool cover -html=cover.out

Output the coverage profile to a file and convert it to a html file

$ go test -coverprofile=cover.out ./...
$ o tool cover -html=cover.out -o cover.html

Clean test cache #

If you see (cached) in results of unit tests

$ go clean -testcache

Setup and shutdown #

func TestMain(m *testing.M) {
	setup()
	code := m.Run()
	shutdown()
	os.Exit(code)
}

func setup() { // Voluntary method name
	// Your code
}

func shutdown() { // Voluntary method name
	// Your code
}

Run subtests in parallel #

func TestSample(t *testing.T) {
	t.Parallel() // Run main test in parallel
	t.Logf("Start: %s", time.Now())
	tests := []struct {
		name string
		code string
		msg  string
	}{
		{"1", "0001", "foo"},
		{"2", "0002", "bar"},
		{"3", "0003", "baz"},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) { // Run subtests
			t.Parallel() // Run subtests in parallel
			if msg := mypkg.Sample(test.code); msg != test.msg {
				t.Errorf("The message must be %s: %s", test.msg, msg)
			}
		})
	}

	t.Logf("End: %s", time.Now())
}

References #