单元测试

简介

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

创立工程目录&文件

mkdir unittest && cd unittest && go mod init unittesttouch calc.go calc_test.go
// calc.gopackage mainfunc 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.gopackage mainimport(    "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    PASSok      unittest        0.003s

基准测试

简介

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

创立工程目录&文件

mkdir benchMarktest && cd benchMarktest && go mod init benchMarktesttouch spf_test.go
// spf_test.gopackage mainimport (    "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: linuxgoarch: amd64pkg: benchMarktestBenchmarkSprintf-4       7432339               163 ns/opPASSok      benchMarktest   1.382s