使用Go进行单元测试的实现
来源:脚本之家
2023-01-07 11:44:19
0浏览
收藏
来到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 <p>在 util_test.go 添加性能测试:<br></p> <pre class="brush:plain;"> // 性能测试 func BenchmarkGenShortID(b *testing.B) { for i := 0; i <p>运行结果如下(使用 --run=none 避免运行普通的测试函数, 因为一般不可能有函数名匹配 none):<br></p> <pre class="brush:plain;"> 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学习网公众号!
版本声明
本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除

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

- 下一篇
- Go语言实现钉钉发送通知
评论列表
-
- 俊逸的枕头
- 这篇文章太及时了,太细致了,受益颇多,已收藏,关注老哥了!希望老哥能多写Golang相关的文章。
- 2023-03-18 01:51:59
查看更多
最新文章
-
- Golang · Go教程 | 12分钟前 |
- Golangdefer作用:资源清理与错误处理结合
- 107浏览 收藏
-
- Golang · Go教程 | 28分钟前 |
- Go语言获取程序名:os.Args[0]与flag用法解析
- 275浏览 收藏
-
- Golang · Go教程 | 28分钟前 |
- Golang实现Base64编码工具教程
- 450浏览 收藏
-
- Golang · Go教程 | 32分钟前 |
- Golang如何实现100%测试覆盖?边界测试技巧分享
- 236浏览 收藏
-
- Golang · Go教程 | 37分钟前 |
- Golang搭建DNA序列分析工具链教程
- 162浏览 收藏
-
- Golang · Go教程 | 37分钟前 |
- Golang实现混沌工程:ChaosMesh实战教程
- 137浏览 收藏
-
- Golang · Go教程 | 38分钟前 |
- Golang提升DevOps配置检测,动态热加载演示
- 478浏览 收藏
-
- Golang · Go教程 | 40分钟前 |
- Go语言Map遍历优化技巧分享
- 480浏览 收藏
-
- Golang · Go教程 | 46分钟前 |
- Golang错误追踪:zap与堆栈集成教程
- 348浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 511次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 498次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
查看更多
AI推荐
-
- 千音漫语
- 千音漫语,北京熠声科技倾力打造的智能声音创作助手,提供AI配音、音视频翻译、语音识别、声音克隆等强大功能,助力有声书制作、视频创作、教育培训等领域,官网:https://qianyin123.com
- 94次使用
-
- MiniWork
- MiniWork是一款智能高效的AI工具平台,专为提升工作与学习效率而设计。整合文本处理、图像生成、营销策划及运营管理等多元AI工具,提供精准智能解决方案,让复杂工作简单高效。
- 89次使用
-
- NoCode
- NoCode (nocode.cn)是领先的无代码开发平台,通过拖放、AI对话等简单操作,助您快速创建各类应用、网站与管理系统。无需编程知识,轻松实现个人生活、商业经营、企业管理多场景需求,大幅降低开发门槛,高效低成本。
- 104次使用
-
- 达医智影
- 达医智影,阿里巴巴达摩院医疗AI创新力作。全球率先利用平扫CT实现“一扫多筛”,仅一次CT扫描即可高效识别多种癌症、急症及慢病,为疾病早期发现提供智能、精准的AI影像早筛解决方案。
- 98次使用
-
- 智慧芽Eureka
- 智慧芽Eureka,专为技术创新打造的AI Agent平台。深度理解专利、研发、生物医药、材料、科创等复杂场景,通过专家级AI Agent精准执行任务,智能化工作流解放70%生产力,让您专注核心创新。
- 95次使用
查看更多
相关文章
-
- Golang 单元测试和基准测试实例详解
- 2022-12-23 275浏览
-
- 一文带你了解Go语言中的单元测试
- 2022-12-27 485浏览
-
- Go单元测试对数据库CRUD进行Mock测试
- 2023-02-25 411浏览
-
- Go语言单元测试模拟服务请求和接口返回
- 2022-12-28 117浏览
-
- Go语言单元测试基础从入门到放弃
- 2023-01-01 301浏览