分享
  1. 首页
  2. 文章

Go单元测试

hatlonely · · 2189 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Go单元测试

简介

单元测试是go语言级别提供的完整功能,测试代码以*_test.go命名,单元测试的case以Test开头,性能测试case以Benchmark开头,运行测试命令:go test <test_file_list>

例子

实现排列组合函数以及对应的单元测试和性能测试

创建工程目录结构

目录结构说明参见规范-项目

└── src
 └── hmath
 ├── hmath.go
 └── hmath_test.go

实现排列组合函数

// src/hmath/hmath.go
package hmath
func combination(m, n int) int {
 if n > m-n {
 n = m - n
 }
 c := 1
 for i := 0; i < n; i++ {
 c *= m - i
 c /= i + 1
 }
 return c
}

实现单元测试和性能测试

// src/hmath/hmath_test.go
package hmath
import (
 "math/rand"
 "testing"
)
// 单元测试
// 测试全局函数,以TestFunction命名
// 测试类成员函数,以TestClass_Function命名
func TestCombination(t *testing.T) {
 // 这里定义一个临时的结构体来存储测试case的参数以及期望的返回值
 for _, unit := range []struct {
 m int
 n int
 expected int
 }{
 {1, 0, 1},
 {4, 1, 4},
 {4, 2, 6},
 {4, 3, 4},
 {4, 4, 1},
 {10, 1, 10},
 {10, 3, 120},
 {10, 7, 120},
 } {
 // 调用排列组合函数,与期望的结果比对,如果不一致输出错误
 if actually := combination(unit.m, unit.n); actually != unit.expected {
 t.Errorf("combination: [%v], actually: [%v]", unit, actually)
 }
 }
}
// 性能测试
func BenchmarkCombination(b *testing.B) {
 // b.N会根据函数的运行时间取一个合适的值
 for i := 0; i < b.N; i++ {
 combination(i+1, rand.Intn(i+1))
 }
}
// 并发测试
func BenchmarkCombinationParallel(b *testing.B) {
 // 测试一个对象或者函数在多线程的场景下面是否安全
 b.RunParallel(func(pb *testing.PB) {
 for pb.Next() {
 m := rand.Intn(100) + 1
 n := rand.Intn(m)
 combination(m, n)
 }
 })
}

运行单元测试和性能测试

export GOPATH=$(pwd)
go test src/hmath/*.go # 单元测试
go test --cover src/hmath/*.go # 单元测试覆盖率
go test -bench=. src/hmath/*.go # 性能测试

上面命令的输出如下:

hatlonely@localhost: ~/hatlonely/github/tmp $ go test src/hmath/hmath*.go
ok command-line-arguments 0.005s
hatlonely@localhost: ~/hatlonely/github/tmp $ go test --cover src/hmath/hmath*.go
ok command-line-arguments 0.005s coverage: 100.0% of statements
hatlonely@localhost: ~/hatlonely/github/tmp $ go test -bench=. src/hmath/*.go
BenchmarkCombination-8 100000 217618 ns/op
BenchmarkCombinationParallel-8 3000000 401 ns/op
PASS
ok command-line-arguments 23.599s

有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:hatlonely

查看原文:Go单元测试

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
2189 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏