Skip to content

test

条件1: xxx_test.go

条件2: TestXxx

然后

sh
go test

go test -v

go test 目录

# 只运行某个 Test
go test -run TestAdd

例1

go
package main

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

import "testing"

func TestAdd(t *testing.T) {

	result := Add(1, 2)

	if result != 3 {
		t.Fatal("Add failed")
	}

}
sh
go test

例2 表驱动测试(Table Driven Test)

go
func TestAdd(t *testing.T) {

	tests := []struct {
		a int
		b int
		expect int
	}{
		{1, 2, 3},
		{2, 3, 5},
		{10, 5, 15},
	}

	for _, tt := range tests {

		result := Add(tt.a, tt.b)

		if result != tt.expect {
			t.Errorf("expect %d got %d", tt.expect, result)
		}

	}

}

断言

失败但继续执行

go
t.Error("message")
// 读了个f
t.Errorf("expect %d got %d", expect, actual)

失败并停止

go
t.Fatal("message")
// 多了个f
t.Fatalf("message")

SubTest

go

func TestAdd(t *testing.T) {

	tests := []struct {
		name   string
		a      int
		b      int
		expect int
	}{
		{"case1", 1, 2, 3},
		{"case2", 2, 3, 5},
	}

	for _, tt := range tests {

        // 重点在 t.Run
		t.Run(tt.name, func(t *testing.T) {

			result := Add(tt.a, tt.b)

			if result != tt.expect {
				t.Errorf("expect %d got %d", tt.expect, result)
			}

		})

	}

}

Benchmark

go
func BenchmarkAdd(b *testing.B) {

	for i := 0; i < b.N; i++ {
		Add(1,2)
	}

}
sh
go test -bench .
sh
BenchmarkAdd-8    1000000000    0.30 ns/op

# 1000000000 是 执行次数
# 0.30 ns/op 是 每次耗时

Test Coverage

sh
go test -cover

go test -coverprofile=cover.out

go tool cover -html=cover.out

TestMain

每个 xxx_test.go 都有自己的 TestMain

Parallel

基于 xxx_test.go 的并行

go
func TestA1(t *testing.T) {
    t.Parallel()
    time.Sleep(1 * time.Second)
}

func TestA2(t *testing.T) {
    t.Parallel()
    time.Sleep(1 * time.Second)
}