使用Go进行单元测试的实现
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《使用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在 util_test.go 添加性能测试:
// 性能测试 func BenchmarkGenShortID(b *testing.B) { for i := 0; i运行结果如下(使用 --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
今天关于《使用Go进行单元测试的实现》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于golang的内容请关注golang学习网公众号!

- 上一篇
- golang环形队列实现代码示例

- 下一篇
- Go语言实现钉钉发送通知
-
- 俊逸的枕头
- 这篇文章太及时了,太细致了,受益颇多,已收藏,关注老哥了!希望老哥能多写Golang相关的文章。
- 2023-03-18 01:51:59
-
- Golang · Go教程 | 34分钟前 |
- DebianSyslog在虚拟机中的实用攻略
- 467浏览 收藏
-
- Golang · Go教程 | 8小时前 |
- DebianOpenSSL安装失败的终极解决方案
- 501浏览 收藏
-
- Golang · Go教程 | 9小时前 |
- Debian数据快速提取技巧
- 216浏览 收藏
-
- Golang · Go教程 | 12小时前 |
- Debian系统JS依赖管理终极攻略
- 218浏览 收藏
-
- Golang · Go教程 | 14小时前 |
- Debian上Hadoop作业调度实用技巧
- 100浏览 收藏
-
- Golang · Go教程 | 14小时前 |
- Go语言闭包误区与匿名函数深度解析
- 222浏览 收藏
-
- Golang · Go教程 | 14小时前 |
- Debian系统安全回收数据的正确攻略
- 111浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 笔灵AI生成答辩PPT
- 探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
- 15次使用
-
- 知网AIGC检测服务系统
- 知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
- 24次使用
-
- AIGC检测-Aibiye
- AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
- 30次使用
-
- 易笔AI论文
- 易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
- 42次使用
-
- 笔启AI论文写作平台
- 笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
- 35次使用
-
- 一文详解Go语言单元测试的原理与使用
- 2022-12-29 377浏览
-
- Golang 单元测试和基准测试实例详解
- 2022-12-23 275浏览
-
- Go单元测试对数据库CRUD进行Mock测试
- 2023-02-25 411浏览
-
- Go语言单元测试模拟服务请求和接口返回
- 2022-12-28 117浏览
-
- Go语言单元测试基础从入门到放弃
- 2023-01-01 301浏览