25 September 2014
Golang源码testing包。

之前看过一本书,说:“凡大神都是先写好单元测试用例,才去写代码的”。我一直都记在心里。今天终于有空,就看了看Golang的测试包testing

谢大的书和Golang官方的文档讲的差不多,Golang提供了两个测试方式:用例测试和压力测试。

1. 用例测试

用例测试的规则我是复制谢大的:

  • 文件名必须是_test.go结尾的,这样在执行go test的时候才会执行到相应的代码
  • 你必须import testing这个包
  • 所有的测试用例函数必须是Test开头
  • 测试用例会按照源代码中写的顺序依次执行
  • 测试函数TestXxx()的参数是testing.T,我们可以使用该类型来记录错误或者是测试状态
  • 测试格式:func TestXxx (t *testing.T),Xxx部分可以为任意的字母数字的组合,但是首字母不能是小写字母[a-z],例如Testintdiv是错误的函数名。
  • 函数中通过调用testing.TError, Errorf, FailNow, Fatal, FatalIf方法,说明测试不通过,调用Log方法用来记录测试的信息。

以我之前写好的堆排序为例进行测试,测试需要以包为单位。对于Golang,就是以文件夹为单位。需要将堆排序文件quicksort.go和测试文件quicksort_test.go放到一起。

验证堆排序测试用例:

func TestHeapSort(t *testing.T) {
	test0 := []int{49, 38, 65, 97, 76, 13, 27, 49}
	test1 := []int{13, 27, 38, 49, 49, 65, 76, 97}
	heapSort(BySortIndex(test0), 0, len(test0))
	for i := 0; i < len(test0); i++ {
		if test0[i] != test1[i] {
			t.Fatal("error")
		}
	}
}

$ go test -v

2. 压力测试

用例测试要用到的是testing.T,而压力测试需要testing.B。它的原型如下:

type B struct {
	common
	N                int
	previousN        int           // number of iterations in the previous run
	previousDuration time.Duration // total duration of the previous run
	benchmark        InternalBenchmark
	bytes            int64
	timerOn          bool
	showAllocResult  bool
	result           BenchmarkResult
	parallelism      int // RunParallel creates parallelism*GOMAXPROCS goroutines
	// The initial states of memStats.Mallocs and memStats.TotalAlloc.
	startAllocs uint64
	startBytes  uint64
	// The net total of this test after being run.
	netAllocs uint64
	netBytes  uint64
}

此结构里面有一个属性N,它表示的是进行压力测试的次数。可以通过b.N = 1234来设置压力次数。

func BenchmarkHeapSort(b *testing.B) {
	b.StopTimer()  //调用该函数停止压力测试的时间计数
	b.StartTimer() //重新开始时间

	b.N = 1234

	for i := 0; i < b.N; i++ {
		test0 := []int{49, 38, 65, 97, 76, 13, 27, 49}
		test1 := []int{13, 27, 38, 49, 49, 65, 76, 97}
		heapSort(BySortIndex(test0), 0, len(test0))
		for i := 0; i < len(test0); i++ {
			if test0[i] != test1[i] {
				b.Fatal("error")
			}
		}
	}
}

$ go test -v -test.bench=".*"
=== RUN TestHeapSort
--- PASS: TestHeapSort (0.00 seconds)
PASS
BenchmarkHeapSort           1234              1620 ns/op
ok      go_code/test    0.051s

这里我只是抛砖引玉,简单写了一点。今后写代码,我也得像大神一下写用例了。大家共勉,哈哈哈。

本文所涉及到的完整源码请参考


参考文献

原文链接:Go语言的测试,转载请注明来源!

EOF