11 go 语言单元测试
//单元测试 go test
// go test 命令是一个按照一定约定和组织的测试代码驱动程序、在包目录中,所有以_test.go为后缀的源码文件都会被go test 运行到
// 我们写的_test.go 源码文件不用担心内容过多,应为go build命令不会将这些测试文件打包到最后的可执行文件。
// test文件有四类 Test开头的功能测试,Benchmark 开头的性能测试 example 和 模糊测试
普通测试:
package ch0921 func add(a, b int) int { return a + b }
package ch0921 import ( "fmt" "testing" ) func TestAdd(t *testing.T) { fmt.Println("123") re := add(5, 6) if re != 11 { t.Errorf("expect %d ,actual is %d", 11, re) } }
结果如下:
=== RUN TestAdd 123 add_test.go:12: expect 11 ,actual is 11 --- FAIL: TestAdd (0.00s) FAIL
--------------------------------------------------------
=== RUN TestAdd
123
--- PASS: TestAdd (0.00s)
PASS
覆盖率执行:
短测试 跳过部分内容:
func TestAdd2(t *testing.T) { fmt.Println("before 456") if testing.Short() { t.Skip("") } fmt.Println("after 456") re := add(3, 9) if re != 12 { t.Errorf("expect %d ,actual is %d", 11, re) } } ====短测试结果如下: F:\goenv\goproject\src\awesomeProject0921\ch0921>go test -short 123 before 456 PASS ok awesomeProject0921/ch0921 0.305s
表格 用例测试。
func TestAdd3(t3 *testing.T) { var db = []struct { a int b int out int }{ {5, 6, 11}, {2, 8, 10}, {16, 7, 13}, {9, 8, 17}, {19, 8, 17}, } for k, v := range db { fmt.Println(k, v) res := add(v.a, v.b) if res != v.out { t3.Errorf("%d和%d值不相等和参数%d", v.a, v.b, v.out) } } }
压力测试
func BenchmarkAdd4(t4 *testing.B) { var a, b, c int a = 10 b = 88 c = 98 for i := 0; i < t4.N; i++ { if ac := add(a, b); ac != c { fmt.Printf("%d 和%d 相加的和不等于%d", a, b, c) } } }
结果如下:
goos: windows goarch: amd64 pkg: awesomeProject0921/ch0921 cpu: Intel(R) Core(TM) i5-7300HQ CPU @ 2.50GHz BenchmarkAdd4 BenchmarkAdd4-4 1000000000 0.3739 ns/op PASS Process finished with the exit code 0
字串各个类型压测速度比较
func BenchmarkAdd4(t4 *testing.B) { var a, b, c int a = 10 b = 88 c = 98 for i := 0; i < t4.N; i++ { if ac := add(a, b); ac != c { fmt.Printf("%d 和%d 相加的和不等于%d", a, b, c) } } } const nm = 10000 func BenchmarkAdd5(t5 *testing.B) { t5.ResetTimer() for i := 0; i < t5.N; i++ { var st string for j := 0; j < nm; j++ { fmt.Printf("%s%d", st, j) } } t5.StopTimer() } func BenchmarkStrAdd6(t6 *testing.B) { t6.ResetTimer() for i := 0; i < t6.N; i++ { var st string for j := 0; j < nm; j++ { st += strconv.Itoa(j) } } t6.StopTimer() } func BenchmarkStrBuilder7(t7 *testing.B) { t7.ResetTimer() for i := 0; i < t7.N; i++ { var stBuilder strings.Builder for j := 0; j < nm; j++ { stBuilder.WriteString(strconv.Itoa(j)) } _ = stBuilder.String() } t7.StopTimer() }
时来天地皆同力,运去英雄不自由