GolangNote

Golang笔记

用go testing 作单元测试压力测试

Permalink

这里是个简单的例子,用go testing 作单元测试压力测试,压力测试可用作性能测试,对比不同的实现方式的性能。

golang 单元测试压力测试

测试的包文件夹 mypack 共有三个文件 :

  • mypack.go 单元功能文件
  • mypack_test.go 单元测试文件
  • mypack_benchmark_test.go 压力测试文件

mypack.go 文件的内容:

Go: mypack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
package mypack

import (
    "errors"
)

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

    return a / b, nil
}

mypack_test.go 的文件内容:

Go: mypack_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package mypack

import (
    "testing"
)

// 输入的参数列表
var fibTests = []struct {
    a        float64 // input
    b        float64 // input
    expected float64 // expected result
}{
    {4, 2, 2},
    {6, 3, 2},
    {100, 10, 10},
    {8, 2, 4},
    {15, 5, 3},
}

func Test_Division_1(t *testing.T) {
    for _, fib := range fibTests {
        if i, e := Division(fib.a, fib.b); i != fib.expected || e != nil { //try a unit test on function
            t.Error("除法函数测试没通过") // 如果不是如预期的那么就报错
        } else {
            t.Log("第一个测试通过了") //记录一些你期望记录的信息
        }
    }
}

func Test_Division_2(t *testing.T) {
    if _, e := Division(6, 0); e == nil { //try a unit test on function
        t.Error("Division did not work as expected.") // 如果不是如预期的那么就报错
    } else {
        t.Log("one test passed.", e) //记录一些你期望记录的信息
    }
}

mypack_benchmark_test.go 的文件内容:

Go: mypack_benchmark_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package mypack

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)
    }
}

切换到这个文件夹下实行:

Bash: go test
1
go test -v -bench=".*"

输出:

Bash: out put
1
2
3
4
5
6
7
8
9
10
11
12
13
14
=== RUN Test_Division_1
--- PASS: Test_Division_1 (0.00s)
    mypack_test.go:25: 第一个测试通过了
    mypack_test.go:25: 第一个测试通过了
    mypack_test.go:25: 第一个测试通过了
    mypack_test.go:25: 第一个测试通过了
    mypack_test.go:25: 第一个测试通过了
=== RUN Test_Division_2
--- PASS: Test_Division_2 (0.00s)
    mypack_test.go:34: one test passed. 除数不能为0
PASS
Benchmark_Division  200000000            6.96 ns/op
Benchmark_TimeConsumingFunction 200000000            6.94 ns/op
ok      _/home/ubuntu/tmp/mypack    4.203s

本文网址: https://golangnote.com/topic/51.html 转摘请注明来源

Related articles

Write a Comment to "用go testing 作单元测试压力测试"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms