go test run 文件_使用 Go 进行单元测试

4b7c2362b32e41d14c62e4cd1e30dd33.png
  • 简介
  • 单元测试
  • 性能测试
  • 性能分析
  • 测试覆盖率
  • 总结
  • 当前部分的代码

简介

日常开发中, 测试是不能缺少的.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Golang中,单元测试是开发人员在编写代码时编写的一种测试方法,它关注代码的局部而不是整体。单元测试的目的是验证代码的各个单元(函数、方法、类等)是否按照预期工作。单元测试通常比其他测试运行得更快,并且可以帮助开发人员在代码编写过程中及时发现和修复问题。\[1\] 在Golang中,我们可以使用testing包来编写和运行单元测试。在测试函数中,我们可以使用testing.T类型的参数来进行断言和错误报告。如果需要跳过某个测试,可以使用testing.T的Skip方法。例如,可以使用testing.Short()函数来判断是否在短模式下运行测试,并使用t.Skip方法跳过测试。\[2\] 要运行Golang的单元测试,可以使用go test命令。默认情况下,go test会运行当前目录下的所有测试文件。可以使用-v选项来输出详细的日志信息。测试运行成功时,会显示PASS,测试失败时,会显示FAIL。如果只想测试单个文件,可以在go test命令后面加上被测试的原文件。如果只想测试单个方法,可以使用-run选项指定要运行的测试方法的名称。\[3\] 希望这些信息对你有帮助! #### 引用[.reference_title] - *1* *2* [Golang单元测试](https://blog.csdn.net/LinAndCurry/article/details/122324323)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Golang-单元测试](https://blog.csdn.net/ALEX_CYL/article/details/121793330)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值