Go语言第十七课 Go的单元测试

go test命令

1、包目录内,所有以_test.go结尾的文件都不是go build编译的一部分!他们都是go test测试的一部分。

2、*_test.go文件中,有三种测试函数:测试函数、基准测试函数、示例测试函数。

测试函数:以Test打头的函数,用于测试一些逻辑是否正确,go test命令跑出来的结果是PASS或者FAIL;

基准测试函数:以Benchmark打头的函数,同于衡量函数的性能,go test跑出来的是多次运行之平均执行时间;

示例函数:以Example打头的函数,go test跑出来的是一个示例文档

测试函数

必须以Test打头,并且Test后跟一个大写打头的函数名,形如

func TestFuckyou(t *testing.T){

}

例如编写fuck_test.go如下

package testExam

import (
	"testing"
	"strings"
)

func TestMytest_1(test *testing.T) {
	Myfunc("aaa", test)
}

func TestMytest_2(test *testing.T) {
	Myfunc("bbb", test)
}

func TestMytest_3(test *testing.T) {
	Myfunc("ccc", test)
}

func Myfunc(str string, test *testing.T) {

	defer func() {
		rec := recover()
		if (rec != nil) {
			test.Error(rec.(error))
		}
	}()
	if strings.Compare(str, "aaa") == 0 {
		a := 0
		a = 1 / a
		return
	}
	if strings.Compare(str, "bbb") == 0 {
		a := 0
		a = 1 / a
		return
	} else {
		a := 1
		a = 1 / a
		return
	}

}
$ go test 
--- FAIL: TestMytest_1 (0.00s)
	fuck_test.go:25: runtime error: integer divide by zero
--- FAIL: TestMytest_2 (0.00s)
	fuck_test.go:25: runtime error: integer divide by zero
FAIL
exit status 1
FAIL	_/home/yong/go/src/testExam	0.002s


猜你喜欢

转载自blog.csdn.net/yongyu_it/article/details/81001481