Go---测试与调优

128 阅读2分钟

写完程序后需要验证程序是否正确,有时候我们会通过main函数来验证程序,但这是不正确的做法,正确的做法是对程序进行测试。

测试

被测函数

// 比较第一个数是否大于第二个数
func Compair(a, b int) bool {
   return a > b
}

单元测试

  • 测试文件一般和被测文件在同一个包下,且已_test结尾,如compair_test
  • 测试方法名以Test开头,且参数是*testing.T类型,如TestCompair(t testing.T)

测试方法

func TestCompair(t *testing.T) {
   // 测试用例
   tests := []struct {
      a, b int
      ans  bool
   }{
      {1, 2, false},
      {3, 4, false},
      {9, 8, true},
   }

   for _, test := range tests {
      if got := Compair(test.a, test.b); got != test.ans {
         t.Errorf("Compair(%d, %d) got %v but expect %v\n", test.a, test.b, got, test.ans)
      }
   }
}

在terminal中执行

go test

测试结果

// 全部成功
=== RUN   TestCompair
--- PASS: TestCompair (0.00s)
PASS
// 部分失败
=== RUN   TestCompair
    compair_test.go:17: Compair(1, 2) got false but expect true

--- FAIL: TestCompair (0.00s)

FAIL

代码覆盖率测试

在terminal中执行

// 将代码覆盖率结果写入到c.out文件中
go test coverprofile c.out

会得到一个c.out文件和如下输出

PASS
coverage: 100.0% of statements
ok      github.com/hell-6/exercise/test 0.255s

我们可以通过tool工具下的cover来通过html页面直观的查看代码覆盖
在terminal中执行

go tool cover -html c.out

执行后会打开一个网页,其中绿色的表示执行到的,红色的表示没有执行到的,这里因为只有一个简单函数,所以都执行到了,覆盖率是百分百

image.png

性能测试

  • 测试方法以Benchmark开头,参数为*testing.B类型,如BenchmarkCompair(b *testing.B) 测试方法
// 性能测试
func BenchmarkCompair(b *testing.B) {
   a, c := 21341512, 3526462213346
   ans := false
   // b.N不可指定,由系统决定
   for i := 0; i < b.N; i++ {
      if got := Compair(a, c); got != ans {
         b.Errorf("Compair(%d, %d) got %v but expect %v\n", a, c, got, ans)
      }
   }
}

在terminal中执行

go test -bench .

得到结果

goos: windows
goarch: amd64
pkg: github.com/exercise/test
cpu: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
BenchmarkCompair-12     1000000000               0.2665 ns/op
PASS
ok      github.com/exercise/test 0.533s

调优

首先在terminal中执行

go test -bench . -cpuprofile cpu.out

上述操作是将测试的cpu性能数据写入cpu.out文件中,cpu.out是一个二进制文件,不能直接查看,要借助tool的pprof调优工具来查看

terminal中执行

go tool pprof cpu.out

然后会出现一个交互式命令行,执行web(需要安装Graphviz)可以更直观得查看信息,方便调优。

image.png