go Test的实现 以及 压力测试

引用

import "testing"

一些原则

  • 文件名必须是 *_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 方法用来记录测试的信息。

另外说明一点,测试函数 _func TestXxxx(t *testing.T)_ 中,除了Xxxx可以不一样外,别的格式都不能改

test 测试用例

比如此处,我们的测试文件 demo_test.go 格式如下:

func Test_Division_1(t *testing.T) {
    if i, e := Division(6, 2); i!=3 || e!=nil { //try a unit test on function
        t.Error("Devision error") // 如果不是如预期的那么就报错
    } else {
        t.Log("Pass test1") //记录一些你期望记录的信息
    }
}

func Test_Division_2(t *testing.T) {
    t.Error("NO ONE CAN PASS")
}

上述的 func Division(float64, float64) (float, error) 函数在 demo.go 文件中如下:

func Division(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("除数不能为0")
    }
    return a / b, nil
}

test 的运行

此时,执行命令,默认运行所有文件

go test

此时我们即可看到结果:

--- FAIL: Test_Division_2 (0.00s)
    demo_test.go:16: 就是不通过
FAIL
exit status 1
FAIL    _/dir/???   0.001s

另外可以使用其他命令,查看能加详细的结果:

go test ???_test.go // 执行指定脚本

go test -v ???_test.go ???.go // 查看详细结果

go test -v -run="Test_Division_2" // 正则匹配函数名称,执行对应的函数

go test -c // 生成test的2进制可执行文件

go test -i // 安装/重新安装运行测试所需的依赖包,但不编译和运行测试代码

go test -o aaa.test// 运行可执行文件

压力测试

作用主要为检测函数(方法)的性能

  • 压力测试用例必须遵循如下格式,其中XXX可以是任意字母数字的组合,但是首字母不能是小写字母,例如 func BenchmarkXxx(b *testing.B) { ... }

  • go test 不会默认执行压力测试的函数,如果要执行压力测试需要带上参数 -test.bench ,语法: -test.bench="test_name_regex" ,例如 go test -test.bench=".*" 表示测试全部的压力测试函数
  • 在压力测试用例中,请记得在循环体内使用testing.B.N,以使测试可以正常的运行
  • 文件名也必须以_test.go结尾

以下为一个名为 webbench_test.go 的Demo:

package gotest

import (
    "testing"
)

func Benchmark_Division(b *testing.B) {
    for i := 0; i < b.N; i++ { //use b.N for looping 
        Division(4, 5)
    }
}

func Benchmark_TimeConsumingFunction(b *testing.B) {
    b.StopTimer() //调用该函数停止压力测试的时间计数

    //此处做一些不会影响测试函数本身的性能的工作

    b.StartTimer() //重新开始时间
    for i := 0; i < b.N; i++ {
        Division(4, 5)
    }
}

执行命令:

go test webbench_test.go -test.bench=".*"

可以得到如下的结果:

goos: linux
goarch: amd64
Benchmark_Division-4                    2000000000           0.56 ns/op
Benchmark_TimeConsumingFunction-4       2000000000           0.47 ns/op
PASS
ok      command-line-arguments  2.153s

参见

一个不错的教程

猜你喜欢

转载自www.cnblogs.com/wangha/p/10428802.html