使用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环形队列实现代码示例
- 上一篇
- golang环形队列实现代码示例
- 下一篇
- Go语言实现钉钉发送通知
-
- 俊逸的枕头
- 这篇文章太及时了,太细致了,受益颇多,已收藏,关注老哥了!希望老哥能多写Golang相关的文章。
- 2023-03-18 01:51:59
-
- Golang · Go教程 | 5分钟前 | go · database/sql · Rows.Scan ·
- Go 扫描未知列数结果时怎么动态分配接收变量
- 328浏览 收藏
-
- Golang · Go教程 | 18分钟前 | Go教程 · database/sql · 数据库元数据 · SQL NULL · Go database/sql rows ColumnTypes ColumnType.Length
- Go RowsColumnTypes 返回长度为 nil 时怎么解释
- 128浏览 收藏
-
- Golang · Go教程 | 27分钟前 |
- Go database/sql 怎么读取查询结果的列类型信息
- 319浏览 收藏
-
- Golang · Go教程 | 41分钟前 |
- Go 证书主机名校验失败时应该查 SAN 还是 CN
- 272浏览 收藏
-
- Golang · Go教程 | 50分钟前 | https · Go教程 · 证书 · tls crypto/x509 CertPool SystemCertPool RootCAs
- Go x509.SystemCertPool 返回空池时怎么兼容不同系统
- 327浏览 收藏
-
- Golang · Go教程 | 55分钟前 |
- Go TLS 客户端连接内网证书时怎么追加自定义 CA
- 255浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Go CheckRedirect 返回错误时怎么读取最后一次响应
- 285浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Go 跟随重定向后 Authorization 为什么消失
- 212浏览 收藏
-
- Golang · Go教程 | 2小时前 |
- Go HTTP Client 禁止自动重定向时怎么保留原始响应
- 458浏览 收藏
-
- Golang · Go教程 | 2小时前 | Go教程 · 结构体标签 · encoding/xml · XML 序列化 · encoding/xml XMLName Go Marshal xml.Name XML 属性
- Go Marshal 输出 XML 时怎么控制根节点和属性
- 278浏览 收藏
-
- Golang · Go教程 | 2小时前 | go · xml · encoding/xml ·
- Go XML 中同名嵌套元素怎么映射成切片
- 380浏览 收藏
-
- Golang · Go教程 | 2小时前 | go · 文本处理 · XML解析 · encoding/xml · Go 命名空间 encoding/xml CharData XMLName
- Go encoding/xml 怎么用 CharData 读取混合文本而不丢空白
- 168浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 25次使用
-
- SuperCLUE
- SuperCLUE是权威的中文大语言模型综合评测基准,涵盖语言理解、知识应用、AI Agent智能体及安全性等12项核心能力。通过多轮对话与客观测试,定期发布榜单与技术报告,为模型研发、优化及行业选型提供科学依据。
- 178次使用
-
- C-Eval
- 深入了解C-Eval中文评估套件,涵盖52个学科与4级难度。本文详解其功能特点、Zero-shot/Few-shot使用方法及代码示例,助您全面评测LLM中文理解与泛化能力。
- 114次使用
-
- AI Prompt Library
- 探索AI Prompt Library免费资源库,涵盖营销、写作及多场景AI提示词。兼容ChatGPT、Claude等工具,一键复制优化输出,提升工作效率。
- 40次使用
-
- Generrated
- Generrated汇集9300+张DALL·E生成图像及对应提示词,支持查看完整图集、对比DALL·E 2与3版本差异,是AI绘图新手学习Prompt设计与获取创作灵感的实用工具。
- 21次使用
-
- 一文详解Go语言单元测试的原理与使用
- 2022-12-29 377浏览
-
- Golang 单元测试和基准测试实例详解
- 2022-12-23 275浏览
-
- 一文带你了解Go语言中的单元测试
- 2022-12-27 485浏览
-
- Go单元测试对数据库CRUD进行Mock测试
- 2023-02-25 411浏览
-
- Go语言单元测试模拟服务请求和接口返回
- 2022-12-28 117浏览

