使用Go进行单元测试的实现
作者:帅气猫咪 发布时间:2024-04-25 15:11:07
标签:Go,单元测试
简介
日常开发中, 测试是不能缺少的.
Go 标准库中有一个叫做 testing 的测试框架, 可以用于单元测试和性能测试.
它是和命令 go test 集成使用的.
测试文件是以后缀 _test.go 命名的, 通常和被测试的文件放在同一个包中.
单元测试
单元测试的格式形如:
func TestAbs(t *testing.T) {
got := Abs(-1)
if got != 1 {
t.Errorf("Abs(-1) = %d; want 1", got)
}
}
在 util 目录下创建一个文件 util_test.go, 添加一个单元测试:
package util
import "testing"
// 普通的测试
func TestGenShortID(t *testing.T) {
shortID, err := GenShortID()
if shortID == "" || err != nil {
t.Error("GenShortID failed")
}
}
然后, 在根目录下运行 go test -v ./util/, 测试结果如下:
root@592402321ce7:/workspace# go test -v ./util/
=== RUN TestGenShortID
--- PASS: TestGenShortID (0.00s)
PASS
ok tzh.com/web/util 0.006s
性能测试
性能测试的结果形如:
func BenchmarkHello(b *testing.B) {
for i := 0; i < b.N; i++ {
fmt.Sprintf("hello")
}
}
在 util_test.go 添加性能测试:
// 性能测试
func BenchmarkGenShortID(b *testing.B) {
for i := 0; i < b.N; i++ {
GenShortID()
}
}
运行结果如下(使用 --run=none 避免运行普通的测试函数, 因为一般不可能有函数名匹配 none):
root@592402321ce7:/workspace# go test -v -bench="BenchmarkGenShortID$" --run=none ./util/
goos: linux
goarch: amd64
pkg: tzh.com/web/util
BenchmarkGenShortID-2 507237 2352 ns/op
PASS
ok tzh.com/web/util 1.229s
这说明, 平均每次运行 GenShortID() 需要 2352 纳秒.
性能分析
运行测试的时候, 可以指定一些参数, 生成性能文件 profile.
-blockprofile block.out
Write a goroutine blocking profile to the specified file
when all tests are complete.
Writes test binary as -c would.
-blockprofilerate n
Control the detail provided in goroutine blocking profiles by
calling runtime.SetBlockProfileRate with n.
See 'go doc runtime.SetBlockProfileRate'.
The profiler aims to sample, on average, one blocking event every
n nanoseconds the program spends blocked. By default,
if -test.blockprofile is set without this flag, all blocking events
are recorded, equivalent to -test.blockprofilerate=1.
-coverprofile cover.out
Write a coverage profile to the file after all tests have passed.
Sets -cover.
-cpuprofile cpu.out
Write a CPU profile to the specified file before exiting.
Writes test binary as -c would.
-memprofile mem.out
Write an allocation profile to the file after all tests have passed.
Writes test binary as -c would.
-memprofilerate n
Enable more precise (and expensive) memory allocation profiles by
setting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.
To profile all memory allocations, use -test.memprofilerate=1.
-mutexprofile mutex.out
Write a mutex contention profile to the specified file
when all tests are complete.
Writes test binary as -c would.
-mutexprofilefraction n
Sample 1 in n stack traces of goroutines holding a
contended mutex.
使用下面的命令, 生成 CPU 的 profile:
go test -v -bench="BenchmarkGenShortID$" --run=none -cpuprofile cpu.out ./util/
当前目录下, 应该会生成 cpu.out 文件和 util.test 文件.
使用下面的命令, 观察耗时操作:
# 进入交互模式
go tool pprof cpu.out
top
安装 Graphviz 后可以生成可视化的分析图.
apt install graphviz
go tool pprof -http=":" cpu.out
测试覆盖率
root@592402321ce7:/workspace# go test -v -coverprofile=cover.out ./util/
=== RUN TestGenShortID
--- PASS: TestGenShortID (0.00s)
PASS
coverage: 9.1% of statements
ok tzh.com/web/util 0.005s coverage: 9.1% of statements
root@592402321ce7:/workspace# go tool cover -func=cover.out
tzh.com/web/util/util.go:12: GenShortID 100.0%
tzh.com/web/util/util.go:17: GetReqID 0.0%
tzh.com/web/util/util.go:22: TimeToStr 0.0%
tzh.com/web/util/util.go:30: GetTag 0.0%
total: (statements) 9.1%
使用 -coverprofile=cover.out 选项可以统计测试覆盖率.使用 go tool cover -func=cover.out 可以查看更加详细的测试覆盖率结果,
统计每个函数的测试覆盖率.
总结
测试是开发中非常重要的一个环节, 用于保证软件质量, 切不可偷懒.
当前部分的代码
作为版本 v0.15.0
来源:https://juejin.im/post/5dc37eb8e51d452a066999bf
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- python压缩和解压缩模块之zlib由于早期的zlib和Python之间不兼容,故推荐1.1.4以后的版本。导入zlib后可以查看版本号&
- 前言Golang 是一种并发友好的语言,使用 goroutines 和 channels 可以轻松地实现多线程爬虫。具体地说,实现的是多协程
- 1.视频分解图片我们使用cv2.VideoCapture来读取视频import cv2cap = cv2.VideoCapture('
- 本文为大家分享了mysql8.0.11客户端无法登陆的解决方法,供大家参考,具体内容如下mysql8.0.11 默认加密方式【caching
- Go语言中符号 “ ^ ” 不再用于次方,而是表示“按位异或的运算”具体的运算规则如下:按位异或 ^ : 两位一个为 0, 一个为 1 ,结
- Python是一种计算机程序设计语言,一种面向对象的动态类型语言,一种脚本语言。最初被设计用于编写自动化脚本(shell)的,常用于各种服务
- python中的多线程是一个非常重要的知识点,今天为大家对多线程进行详细的说明,代码中的注释有多线程的知识点还有测试用的实例。import
- 当在一个分支的开发工作未完成,却又要切换到另外一个分支进行开发的时候,除了commit原分支的代码改动的方法外,我觉得git st
- 1. 创建shell脚本 vim backupdb.sh 创建脚本内容如下: #!/bin/sh db_user="root&qu
- 前后端分离的开发模式,原本觉得没什么稀奇的玩艺,在最近参与的一个大型项目中,让我有了更深的理解。前后端分离的开发模式:系统分析阶段,系分和前
- 对于python语言的True和False我们并不陌生了,在学习的过程中常会遇到这样的返回值,那么True真和False假的具体含义是什么?
- 今天解析DEDECMS时发现deder的MYSQL时间字段,都是用`senddata` int(10) unsigned NOT NULL
- 本文实例讲述了python实现复制整个目录的方法。分享给大家供大家参考。具体分析如下:python有一个非常好用的目录操作类库shutil,
- 这个是用python实现的基本的增删改查的学生管理系统吧,其中主要是对输入的数据进行合法性检测的问题,这次又对函数进行了练习!掌握函数更加熟
- 前言:Turtle库是Python语言中一个很流行的绘制图像的函数库,想象一个小乌龟,在一个横轴为x、纵轴为y的坐标系原点,(0,0)位置开
- 本文实例讲述了Laravel框架路由管理。分享给大家供大家参考,具体如下:路由中输出视图Route::get('/', fu
- expect脚本expect是什么expect是一个免费的编程工具,用来实现自动的交互式任务,而无需人为干预。说白了,expect就是一套用
- 条件判断计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用if
- 散点图和折线图是数据分析中最常用的两种图形。其中,折线图用于分析自变量和因变量之间的趋势关系,最适合用于显示随着时间而变化的连续数据,同时还
- NumPy广播(Broadcast),广播(Broadcast)是 numpy 对不同形状(shape)的数组进行数值计算的方式, 对数组的