• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

go单元测试

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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:\project\src\go_dev\design_pattern\singleton>go test
PASS
ok      go_dev/design_pattern/singleton 0.346s

  

查看测试代码覆盖率

go test -coverprofile=c.out
go tool cover -html=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

  

  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
转Go语言structtag介绍发布时间:2022-07-10
下一篇:
go切片的创建方式发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap