go单元测试

testing模块

  • 测试代码放在当前包以_test.go结尾的文件中
  • 测试函数以Test为名称前缀
  • 测试命令(go test)
  • 正常编译操作(go build/install)会忽略测试文件

单例模式举例

singleton.go

package singleton

import (
	"sync"
)

type Singleton struct{}

var (
	singleton *Singleton
	once      sync.Once
)

func GetInstance() *Singleton {
	once.Do(func() {
		singleton = &Singleton{}
	})
	return singleton
}

  

singleton_test.go

package singleton

import "testing"

func TestSingleton(t *testing.T) {
	ins1 := GetInstance()
	ins2 := GetInstance()
	if ins1 != ins2 {
		t.Fatal("instance is not equal")
	}
}

  

终端执行go test,会执行singleton_test.go里面写的测试用例

D:projectsrcgo_devdesign_patternsingleton>go test
PASS
ok      go_dev/design_pattern/singleton 0.346s

  

查看测试代码覆盖率

go test -coverprofile=c.out
go tool cover -html=c.out

  

输出

D:projectsrcgo_devdesign_patternsingleton>go test -coverprofile=c.out
PASS
coverage: 100.0% of statements
ok      go_dev/design_pattern/singleton 0.324s

  

性能测试(_test.go)

func BenchSingleton(b *testing.B) {
	ins1 := GetInstance()
	ins2 := GetInstance()
	for i := 0; i < b.N; i++ {
		if ins1 != ins2 {
			b.Fatal("instance is not equal")
		}
	}
}

  

执行

go test -bench .

  

分析性能

D:projectsrcgo_devdesign_patternsingleton>go test -bench . -cpuprofile cpu.out
D:projectsrcgo_devdesign_patternsingleton>go tool pprof cpu.out
Type: cpu
Time: Aug 23, 2018 at 11:33am (CST)
Duration: 200ms, Total samples = 0
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) web