通过测试学习 Go 编程
TDD 简介
TDD是测试驱动开发(Test-Driven Development)的英文简称,是敏捷开发中的一项核心实践和技术,也是一种设计方法论。TDD的原理是在开发功能代码之前,先编写单元测试用例代码,测试代码确定需要编写什么产品代码。TDD虽是敏捷方法的核心实践,但不只适用于XP(Extreme Programming),同样可以适用于其他开发方法和过程。
TDD 三条规则
- You are not allowed to write any production code unless it is to make a failing unit test pass.
- 除非为了使一个失败的unit test通过,否则不允许编写任何产品代码
- You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
- 在一个单元测试中只允许编写刚好能够导致失败的内容(编译错误也算失败)
- You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
- 只允许编写刚好能够使一个失败的unit test通过的产品代码
Go 编写测试规则
规则
- go 文件以
xxx_test
命名 - 测试函数命名必须以单词
Test
开始 - 测试函数只接受一个参数
t *testing.T
示例:
package main
import "testing"
func TestHello(t *testing.T) {
got := Hello()
want := "Hello, world"
if got != want {
t.Errorf("got %q want %q", got, want)
}
}
Go 测试函数运行
用法
usage: go test [build/test flags] [packages] [build/test flags & test binary flags]
flags 介绍
-
go test -c package_import_path
-
-c
把指定包编译为二进制文件, 需要手动执行二进制文件运行 - 示例:
-
go test -c
不指定包则编译当前包为二进制文件 -
go test -c src/hell
指定包路径则编译指定包为二进制文件
-
-
-
go test -exec binary file
-
-exec
运行二进制文件测试 -
示例:
-
go test -exec .\array.test.exe
执行二进制文件测试运行结果:
PASS ok test/array 0.073s
-
-
-
go test -json
-
-json
运行测试,并将结果输出为json
格式 -
示例:
-
go test -json
执行当前测试文件运行结果:
{"Time":"2021-08-29T01:02:12.4280929+08:00","Action":"run","Package":"test/array","Test":"TestSum"} ... {"Time":"2021-08-29T01:02:12.4512596+08:00","Action":"pass","Package":"test/array","Elapsed":0.091}
-
-
-
go test -o filename
-
-o
把测试编译成自己命名二进制包, 默认仍然会运行测试(除非指定-c
或者-i
) -
示例:
-
go test -o .\sum_test1.go
[^ 1 ]运行结果:
PASS ok test/array 0.073s
-
-
-
go test -bench regexp
-
-bench
运行基准测试,默认不运行 -
示例:
-
go test -bench="."
[^ 2 ]运行结果:
goos: windows goarch: amd64 pkg: test/repeat cpu: 11th Gen Intel(R) Core(TM) i5-11300H @ 3.10GHz BenchmarkRepeat-8 8069515 133.6 ns/op PASS ok test/repeat 1.309s
-
-
-
go test -benchtime
-
-benchtime
基准测试,持续时间(默认1秒) - 示例:
-
go test -benchtime
[^ 3 ]
-
-
-
go test -count
-
-count
运行测试次数 -
示例:
-
go test -count="10" -bench="."
运行结果:
goos: windows goarch: amd64 pkg: test/repeat cpu: 11th Gen Intel(R) Core(TM) i5-11300H @ 3.10GHz BenchmarkRepeat-8 5511104 186.0 ns/op BenchmarkRepeat-8 6716119 163.3 ns/op PASS ok test/repeat 2.630s
-
-
-
go test -cover
-
-cover
覆盖率统计 -
示例:
-
go test -cover
运行结果:
PASS coverage: 100.0% of statements ok test/repeat 0.101s
-
-
-
go test -list regexp
-
-list
列出匹配的测试 -
示例:
-
go test -list t
运行结果:
TestSum TestSumAll TestSumAllTails ok test/array 0.096s
-
-
-
go test -v
-
-v
详细输出运行时记录所有的测试
-
[^ 1 ]: 不太理解这-o
flag
使用
[^ 2 ]: 支持运行指定的基准测试,例如:-bench=正则表达式
尚不清楚如何使用
[^ 3 ]: 如何指定时间尚不清楚