关于go:Go-单元基准测试

5次阅读

共计 1241 个字符,预计需要花费 4 分钟才能阅读完成。

单元测试

简介

 单元测试的代码文件必须以_test.go 结尾
单元测试的函数必须以 Test 结尾,必须是可导出的
单元测试用的参数有且只有一个,在这里是 t *testing.T
单元测试函数不能有返回值 

创立工程目录 & 文件

mkdir unittest && cd unittest && go mod init unittest
touch calc.go calc_test.go
// calc.go
package main


func Add(a, b int) int {return a + b}

func Sub(a, b int) int {return a - b}

func Mul(a, b int) int {return a * b}
// calc_test.go
package main

import("testing")

func TestAdd(t *testing.T){if ret := Add(8, 8); ret != 16 {t.Errorf("8 + 8 equal to 16, but %d got", ret)
    }

    if ret := Add(2, 6); ret != 8 {t.Errorf("2 + 6 equal to 16, but %d got", ret)
    }
}

func TestSub(t *testing.T){if ret := Sub(8, 8); ret != 0 {t.Errorf("8 - 8 equal to 0, but %d got", ret)
    }

    if ret := Sub(2, 6); ret != -4 {t.Errorf("2 - 6 equal to -4, but %d got", ret)
    }
}

func TestMul(t *testing.T){if ret := Mul(8, 8); ret != 64 {t.Errorf("8 * 8 equal to 64, but %d got", ret)
    }

    if ret := Mul(2, 6); ret != 12 {t.Errorf("2 * 6 equal to 12, but %d got", ret)
    }
}

运行

$  go test    
PASS
ok      unittest        0.003s

基准测试

简介

 基准测试的代码文件必须以_test.go 结尾
基准测试的函数必须以 Benchmark 结尾,必须是可导出的
基准测试函数必须承受一个指向 Benchmark 类型的指针作为惟一参数
基准测试函数不能有返回值 

创立工程目录 & 文件

mkdir benchMarktest && cd benchMarktest && go mod init benchMarktest
touch spf_test.go
// spf_test.go
package main

import (
    "fmt"
    "testing"
)

func BenchmarkSprintf(b *testing.B) {
    num := 1000
    b.ResetTimer()
    for i := 0; i < b.N; i++ {fmt.Sprintf("%d", num)
    }
}

运行

$ go test -bench=.                        
goos: linux
goarch: amd64
pkg: benchMarktest
BenchmarkSprintf-4       7432339               163 ns/op
PASS
ok      benchMarktest   1.382s
正文完
 0