使用Go进行单元测试的实现

 更新时间:2019年11月07日 14:52:06   作者:帅气猫咪  
这篇文章主要介绍了使用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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Go操作各大消息队列教程(RabbitMQ、Kafka)

    Go操作各大消息队列教程(RabbitMQ、Kafka)

    消息队列是一种异步的服务间通信方式,适用于无服务器和微服务架构,本文主要介绍了Go操作各大消息队列教程(RabbitMQ、Kafka),需要的朋友可以了解一下
    2024-02-02
  • GoLang 中的随机数的示例代码

    GoLang 中的随机数的示例代码

    本篇文章主要介绍了GoLang 中的随机数的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-03-03
  • go zero微服务实战系服务拆分

    go zero微服务实战系服务拆分

    这篇文章主要为大家介绍了go zero微服务实战系服务拆分的示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • Go语言普通指针unsafe.Pointer uintpt之间的关系及指针运算

    Go语言普通指针unsafe.Pointer uintpt之间的关系及指针运算

    这篇文章主要为大家介绍了Go语言普通指针unsafe.Pointer uintpt之间的关系及指针运算示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • go mongox简洁高效文档操作及bson数据构造流畅技巧

    go mongox简洁高效文档操作及bson数据构造流畅技巧

    这篇文章主要为大家介绍了go mongox简洁高效文档操作及bson数据构造流畅技巧示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-11-11
  • Go语言实现分布式锁

    Go语言实现分布式锁

    分布式锁是控制分布式系统之间同步访问共享资源的一种方式。如果不同的系统或是同一个系统的不同主机之间共享了一个或一组资源,那么访问这些资源时,需要通过一些互斥手段来防止彼此之间的干扰以保证一致性,在这种情况下,就需要使用分布式锁了
    2023-01-01
  • 详解Go语言中iota的应用

    详解Go语言中iota的应用

    在本文中,小编将带着大家深入探讨 iota 的神奇力量,包括 iota 的介绍和应用场景以及使用技巧和注意事项,准备好了吗,准备一杯你最喜欢的饮料或茶,随着本文一探究竟吧
    2023-07-07
  • Go语言的文件操作代码汇总

    Go语言的文件操作代码汇总

    本文给大家汇总介绍了go语言中的文件操作的代码,包括文件的读写,文件的新建打开和删除等,希望对大家学习go语言能够有所帮助
    2018-10-10
  • Go读取配置文件的方法总结

    Go读取配置文件的方法总结

    我们常见的配置文件的格式一般有:XML、JSON、INI、YAML、env和.properties,本文小编为大家整理了Go语言读取这些格式的配置文件的方法,希望对大家有所帮助
    2023-10-10
  • Golang使用Gin框架实现路由分类处理请求流程详解

    Golang使用Gin框架实现路由分类处理请求流程详解

    Gin是一个golang的微框架,封装比较优雅,具有快速灵活,容错方便等特点,这篇文章主要介绍了Golang使用Gin框架实现路由分类处理请求,感兴趣的同学可以参考下文
    2023-05-05

最新评论