Go 功能测试与性能测试

1、功能测试

calcTriangle.go

// 需要被测试的函数
func calcTriangle(a, b int) int {
    return int(math.Sqrt(float64(a*a + b*b)))
}

calcTriangle_test.go // 注意测试文件必须以_test结尾

package main

import "testing"

// 注意测试函数必须以 Test开头 func TestTriangle(t *testing.T) {
// 表格驱动测试 tests := []struct {a, b, c int} { {3,4,5}, {5,12,13}, {8,15,17}, {12,35,37}, {30000,40000,50000}, } for _, tt := range tests { if actual := calcTriangle(tt.a, tt.b); actual != tt.c { t.Errorf("calcTriangle(%d, %d); got %d; expected %d", tt.a, tt.b, actual, tt.c) } } }

测试执行方法

1、IDE中直接执行

2、命令行 go test .

代码覆盖率测试

命令行执行:

1、go test -coverprofile=c.out  生成覆盖率数据

2、go tool cover -html c.out  生成html页面展示

2、性能测试

nonrepeating.go

package main

import "fmt"

func lengthOfNonRepeatingSubStr(s string) int {
    lastOccurred := make(map[rune]int)
    start := 0
    maxLength := 0
    for i, ch := range []rune(s) {
        if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
            start = lastI + 1
        }
        if i - start + 1 > maxLength {
            maxLength = i - start + 1
        }
        lastOccurred[ch] = i
        }
    return maxLength
}

func main() {
    fmt.Println(
        lengthOfNonRepeatingSubStr("abcabcbb"))
    fmt.Println(
        lengthOfNonRepeatingSubStr("bbbbb"))
    fmt.Println(
        lengthOfNonRepeatingSubStr("pwwkew"))
    fmt.Println(
        lengthOfNonRepeatingSubStr(""))
    fmt.Println(
        lengthOfNonRepeatingSubStr("b"))
    fmt.Println(
        lengthOfNonRepeatingSubStr("abcdef"))
    fmt.Println(
        lengthOfNonRepeatingSubStr("这里是慕课网"))
    fmt.Println(
        lengthOfNonRepeatingSubStr("一二三二一"))
    fmt.Println(
        lengthOfNonRepeatingSubStr(
            "黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花"))
}

nonrepeating_test.go

package main

import "testing"

// 功能测试
func TestSubstr(t *testing.T) {
    tests := []struct{s string; ans int} {
        {"abcabcbb", 3},
        {"bbbbb", 1},
        {"pwwkew", 3},
        {"", 0},
        {"b", 1},
        {"abcdef", 6},
        {"这里是慕课网", 6},
        {"一二三二一", 3},
        {"黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花", 8},
    }

    for _, tt := range tests {
        if actual := lengthOfNonRepeatingSubStr(tt.s); actual != tt.ans {
            t.Errorf("got %d for input %s; expected %d", actual, tt.s, tt.ans)
        }
    }
}

// 性能测试
func BenchmarkSubstr(b *testing.B) {
    s := "黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花"
    ans := 8

    // b.N 自动判断测试的次数
    for i := 0; i < b.N ; i++ {
        actual := lengthOfNonRepeatingSubStr(s)
        if actual != ans {
            b.Errorf("got %d for input %s; expected %d", actual, s, ans)
        }
    }
}

测试执行方法

1、IDE中直接执行

2、命令行 go test -bench .

3、go test -bench . -cpuprofile=cpu.out , go tool pprof 生成SVG图形