Go工程测试|青训营笔记

93 阅读1分钟

Go工程测试|青训营笔记

这是我参与「第五届青训营 」伴学笔记创作活动的第3天

测试是避免事故发生的最后一个屏障

测试金字塔

image-20230116123439073

1.单元测试

image-20230116123930610

1.1 测试规范

image-20230116124244839

例子:

  • 使用go官方testing进行测试
  • 使用assert判断字符串是否相等
package main
​
import "testing"func HelloTom() string {
  return "Jerry"
}
​
func TestHelloTom(t *testing.T) {
  output := HelloTom()
  expectOutput := "Tom"
  if output != expectOutput {
    t.Errorf("expected:%s,actual:%s", expectOutput, output)
  }
}

终端运行:

go test hello_test.go

运行结果:

image-20230116130207261

assert库用来测试很方便

1.2 覆盖率

经过测试案例后所有运行过的代码比上所有代码

image-20230116130414443

image-20230116130809686

一般覆盖率:50%-60%

较高覆盖率:80%(一些重要组件)

测试分支相互独立、全面覆盖

测试单元颗粒足够小、函数单一职责

1.3 依赖测试

各个时间进行测试均是稳定的

image-20230116131144136

1.4 Mock

对函数、方法进行拷贝,建立一个独立的环境(不依赖本地文件),防止测试的时候本地文件被别人篡改引起的测试问题

image-20230116131420683

2.基准测试

image-20230116131759685

例子:

package benchmark
​
import (
  "github.com/bytedance/gopkg/lang/fastrand"
  "math/rand"
)
​
var ServerIndex [10]intfunc InitServerIndex() {
  for i := 0; i < 10; i++ {
    ServerIndex[i] = i+100
  }
}
​
func Select() int {
  return ServerIndex[rand.Intn(10)]
}
​
func FastSelect() int {
  return ServerIndex[fastrand.Intn(10)] //fastrand性能好很多
}
package benchmark
​
import (
  "testing"
)
​
func BenchmarkSelect(b *testing.B) { //串行
  InitServerIndex()
  b.ResetTimer()
  for i := 0; i < b.N; i++ {
    Select()
  }
}
func BenchmarkSelectParallel(b *testing.B) { //并行
  InitServerIndex()
  b.ResetTimer()
  b.RunParallel(func(pb *testing.PB) {
    for pb.Next() {
      Select()
    }
  })
}
func BenchmarkFastSelectParallel(b *testing.B) {
  InitServerIndex()
  b.ResetTimer()
  b.RunParallel(func(pb *testing.PB) {
    for pb.Next() {
      FastSelect()
    }
  })
}

运行结果:

image-20230116134749261

猜测:第二个并行比第一个串行慢是因为rand为了保证安全加了锁