在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
testing模块
单例模式举例 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:\project\src\go_dev\design_pattern\singleton>go test PASS ok go_dev/design_pattern/singleton 0.346s
查看测试代码覆盖率 go test -coverprofile=c.out
输出 D:\project\src\go_dev\design_pattern\singleton>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:\project\src\go_dev\design_pattern\singleton>go test -bench . -cpuprofile cpu.out D:\project\src\go_dev\design_pattern\singleton>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
|
请发表评论