go 单元测试

基础测试

基本满足预期的功能,简单快速,可用于测试驱动开发

表格测试

特意构建的一组输入,包含关注点,特别是边界条件是否满足

随机测试

随机输入扩展测试的覆盖范围.预期的结果的获得.

  • 算法清晰但性能不佳的函数来得到可信结果,再和被测试函数的输出比较
  • 构建符合特定规律的输入,就能知道结果,再和被测函数的输出比较

例子

源码文件

//fib.go
package main

//
func FibRaw(x int) int {
	if x == 0 {
		return 0
	} else if x <= 2 {
		return 1
	} else {
		return FibRaw(x-2) + FibRaw(x-1)
	}
}

//
var cache = make(map[int]int)

func FibCache(x int) int {
	if val, found := cache[x]; found {
		return val
	}

	var ret int
	if x == 0 {
		ret = 0
	} else if x <= 2 {
		ret = 1
	} else {
		ret = FibCache(x-2) + FibCache(x-1)
	}

	cache[x] = ret
	return ret
}

测试文件

//fib_test.go
package main

import (
	"math/rand"
	"testing"
	"time"
)

//test
//基础测试
func TestFibCacheBasic(t *testing.T) {
	input := 5
	want := 5
	got := FibCache(input)
	if got != want {
		t.Errorf("fibMen(%v) = %v,want %v", input, got, want)
	}
}

//表格测试
func TestFibCacheTable(t *testing.T) {
	var tests = []struct {
		input int
		want  int
	}{
		{0, 0},
		{1, 1},
		{2, 1},
		{3, 2},
		{4, 3},
		{5, 5},
		{6, 8},
	}
	for _, test := range tests {
		if got := FibCache(test.input); got != test.want {
			t.Errorf("fibMen(%v) = %v,want %v", test.input, got, test.want)
		}
	}
}

//随机测试
func TestFibCacheRandom(t *testing.T) {

	seed := time.Now().UTC().UnixNano()
	rng := rand.New(rand.NewSource(seed))
	for i := 0; i < 100; i++ {
		input := rng.Intn(40)
		got := FibCache(input)
		want := FibRaw(input)
		if got != want {
			t.Errorf("fibMen(%v) = %v,want %v", input, got, want)
		}
	}

}

运行测试

运行全部测试用例,用 . 模式匹配所有功能测试用例

$ go test -v -run=.
=== RUN   TestFibCacheBasic
--- PASS: TestFibCacheBasic (0.00s)
=== RUN   TestFibCacheTable
--- PASS: TestFibCacheTable (0.00s)
=== RUN   TestFibCacheRandom
--- PASS: TestFibCacheRandom (2.21s)
PASS
ok      _/mnt/i/github.com/fuwensun_blog_dev/go_bench_test/src/fib      2.267s

运行某一类测试用例,比如 Basic 或 Table 耗时短的

$ go test -v -run="Basic|Table"
=== RUN   TestFibCacheBasic
--- PASS: TestFibCacheBasic (0.00s)
=== RUN   TestFibCacheTable
--- PASS: TestFibCacheTable (0.00s)
PASS
ok      _/mnt/i/github.com/fuwensun_blog_dev/go_bench_test/src/fib      0.082s

Randrom 耗时长,有时间了单独运行

$ go test -v -run=Random
=== RUN   TestFibCacheRandom
--- PASS: TestFibCacheRandom (3.31s)
PASS
ok      _/mnt/i/github.com/fuwensun_blog_dev/go_bench_test/src/fib      3.387s

查看本次测试覆盖率

$ go test -cover
PASS
coverage: 34.1% of statements
ok      _/mnt/i/github.com/fuwensun_blog_dev/go_bench_test/src/fib      4.145s

覆盖率分析

运行测试并生成覆盖率分析日志

$ go test -v -run=Random -coverprofile=cover.out
=== RUN   TestFibCacheRandom
--- PASS: TestFibCacheRandom (4.21s)
PASS
coverage: 34.1% of statements
ok      _/mnt/i/github.com/fuwensun_blog_dev/go_bench_test/src/fib      4.277s

用 cover 工具处理日志,生成一个 html 报告

$ go tool cover -html=cover.out -o cover.html

go 单元测试_第1张图片

你可能感兴趣的:(go)