分享
  1. 首页
  2. 文章

Go 如何编写简洁测试 -- 表格驱动测试

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

表格驱动测试是一种编写易于扩展测试用例的测试方法。表格驱动测试在 Go 语言中很常见(并非唯一),以至于很多标准库<sup>[1](#reference)</sup>都有使用。表格驱动测试使用匿名结构体。 在这篇文章中我会告诉你如何编写表格驱动测试。继续使用 [errline repo](https://github.com/virup/errline) 这个项目,现在我们来为 `Wrap()` 函数添加测试。`Wrap()` 函数用于给一个 `error` 在调用位置添加文件名和行数的修饰。我们尤其需要测试其中计算文件的短名称的逻辑(以粗体表示部分)。最初的 `Wrap()` 函数如下: <pre> func Wrap(err error) error { if err == nil { return nil } // If error already has file line do not add it again. if _, ok := err.(*withFileLine); ok { return err } _, file, line, ok := runtime.Caller(calldepth) if !ok { file = "???" line = 0 } <b>short := file for i := len(file) - 1; i > 0; i-- { if file[i] == '/' { short = file[i+1:] break } } file = short</b> return &withFileLine{err, file, line} } </pre> 为了测试短文件名计算的逻辑更加简便,我们将这部分逻辑提取出来作为函数 `getShortFilename()`。代码现在变成这样: <pre> func Wrap(err error) error { if err == nil { return nil } // If error already has file line do not add it again. if _, ok := err.(*withFileLine); ok { return err } _, file, line, ok := runtime.Caller(calldepth) if !ok { file = "???" line = 0 } file = getShortFilename(file) return &withFileLine{err, file, line} } func <b>getShortFilename(file string)</b> string { short := file for i := len(file) - 1; i > 0; i-- { if file[i] == '/' { short = file[i+1:] break } } file = short return file } </pre> 通过重构代码使其便于测试是很常见的做法。 我们现在通过传递多个文件名参数来测试 `getShortFilename()`,验证其输出结果是否符合预期。 我们先从一个空的测试函数开始: ```go func TestShortFilename(t *testing.T) { } ``` 紧接着,我们引入一个包含字段 `in` 和 `expected` 的匿名结构体(struct)。`in` 表示传递给 `getShortFilename()` 的参数,`expected` 则代表我们预期的返回结果。`tests` 是包含多个这样结构体的一个数组。 ```go func TestShortFilename(t *testing.T) { tests := []struct { in string // input expected string // expected result }{ {"???", "???"}, {"filename.go", "filename.go"}, {"hello/filename.go", "filename.go"}, {"main/hello/filename.go", "filename.go"}, } } ``` 有了这个,我们就能通过循环来实现我们的测试方法。 ```go func TestShortFilename(t *testing.T) { tests := []struct { in string expected string }{ {"???", "???"}, {"filename.go", "filename.go"}, {"hello/filename.go", "filename.go"}, {"main/hello/filename.go", "filename.go"}, } for _, tt := range tests { actual := getShortFilename(tt.in) if strings.Compare(actual, tt.expected) != 0 { t.Fail() } } } ``` 可以注意到,添加测试用例极其简单,只需在 `tests` 中添加项目即可。 这个方案可以扩展以适应于测试接受和返回多个参数的方法。 就这样了。 代码可以从 [我的 github](https://github.com/virup/errline/tree/master) 获取。 ## <p id="reference">引用</p> 1. 一些 Go 语言标准库的表格驱动测试例子 * [https://github.com/golang/go/blob/master/src/strconv/ftoa_test.go](https://github.com/golang/go/blob/master/src/strconv/ftoa_test.go) * [https://github.com/golang/go/blob/master/src/path/match_test.go](https://github.com/golang/go/blob/master/src/path/match_test.go) * [https://github.com/golang/go/blob/master/src/archive/tar/strconv_test.go](https://github.com/golang/go/blob/master/src/archive/tar/strconv_test.go)

via: https://medium.com/@virup/how-to-write-concise-tests-table-driven-tests-ed672c502ae4

作者:Viru 译者:alfred-zhong 校对:polaris1119

本文由 GCTT 原创编译,Go语言中文网 荣誉推出

本文由 GCTT 原创翻译,Go语言中文网 首发。也想加入译者行列,为开源做一些自己的贡献么?欢迎加入 GCTT!
翻译工作和译文发表仅用于学习和交流目的,翻译工作遵照 CC-BY-NC-SA 协议规定,如果我们的工作有侵犯到您的权益,请及时联系我们。

欢迎遵照 CC-BY-NC-SA 协议规定 转载,敬请在正文中标注并保留原文/译文链接和作者/译者等信息。
文章仅代表作者的知识和看法,如有不同观点,请楼下排队吐槽


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

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

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

用户登录

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

今日阅读排行

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

一周阅读排行

    加载中

关注我

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

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

给该专栏投稿 写篇新文章

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

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