Golang测试技术

发表于:2015-5-25 11:36

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:bigwhite    来源:51Testing软件测试网采编

  本篇文章内容来源于Golang核心开发组成员Andrew Gerrand在Google I/O 2014的一次主题分享“Testing Techniques”,即介绍使用Golang开发 时会使用到的测试技术(主要针对单元测试),包括基本技术、高级技术(并发测试、mock/fake、竞争条件测试、并发测试、内/外部测 试、vet工具等)等,感觉总结的很全面,这里整理记录下来,希望能给大家带来帮助。原Slide访问需要自己搭梯子。另外这里也要吐槽一 下:Golang官方站的slide都是以一种特有的golang artical的格式放出的(用这个工具http://go-talks.appspot.com/可以在线观看),没法像pdf那样下载,在国内使用和传播极其不便。
  一、基础测试技术
  1、测试Go代码
  Go语言内置测试框架。
  内置的测试框架通过testing包以及go test命令来提供测试功能。
  下面是一个完整的测试strings.Index函数的完整测试文件:
//strings_test.go (这里样例代码放入strings_test.go文件中)
package strings_test
import (
"strings"
"testing"
)
func TestIndex(t *testing.T) {
const s, sep, want = "chicken", "ken", 4
got := strings.Index(s, sep)
if got != want {
t.Errorf("Index(%q,%q) = %v; want %v", s, sep, got, want)//注意原slide中的got和want写反了
}
}
$go test -v strings_test.go
=== RUN TestIndex
— PASS: TestIndex (0.00 seconds)
PASS
ok      command-line-arguments    0.007s
go test的-v选项是表示输出详细的执行信息。
将代码中的want常量值修改为3,我们制造一个无法通过的测试:
$go test -v strings_test.go
=== RUN TestIndex
— FAIL: TestIndex (0.00 seconds)
strings_test.go:12: Index("chicken","ken") = 4; want 3
FAIL
exit status 1
FAIL    command-line-arguments    0.008s
  2、表驱动测试
Golang的struct字面值(struct literals)语法让我们可以轻松写出表驱动测试。
package strings_test
import (
"strings"
"testing"
)
func TestIndex(t *testing.T) {
var tests = []struct {
s   string
sep string
out int
}{
{"", "", 0},
{"", "a", -1},
{"fo", "foo", -1},
{"foo", "foo", 0},
{"oofofoofooo", "f", 2},
// etc
}
for _, test := range tests {
actual := strings.Index(test.s, test.sep)
if actual != test.out {
t.Errorf("Index(%q,%q) = %v; want %v",
test.s, test.sep, actual, test.out)
}
}
}
$go test -v strings_test.go
=== RUN TestIndex
— PASS: TestIndex (0.00 seconds)
PASS
ok      command-line-arguments    0.007s
31/3123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号