From 687d52acca027d37a585496cfdc13cf6acfd3c03 Mon Sep 17 00:00:00 2001 From: dake Date: Sun, 8 Nov 2015 22:53:05 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BF=BB=E8=AF=9113.9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- eBook/13.10.md | 2 ++ eBook/13.9.md | 61 +++++++++++++++++++++++++++++++++++++++++++++- eBook/directory.md | 1 + 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 eBook/13.10.md diff --git a/eBook/13.10.md b/eBook/13.10.md new file mode 100644 index 0000000..1b20f45 --- /dev/null +++ b/eBook/13.10.md @@ -0,0 +1,2 @@ +# 13.10 性能调试:分析并优化 Go 程序 + diff --git a/eBook/13.9.md b/eBook/13.9.md index 2ca647b..2f1e266 100644 --- a/eBook/13.9.md +++ b/eBook/13.9.md @@ -1 +1,60 @@ -# 13.9 用(测试数据)表驱动测试 \ No newline at end of file +# 13.9 用(测试数据)表驱动测试 + +编写测试代码时,一个较好的办法是把测试的输入数据和期望的结果写在一起组成一个数据表:表中的每条记录都是一个含有输入和期望值的完整测试用例,有时还可以结合像测试名字这样的额外信息来让测试输出更多的信息。 + +实际测试时简单迭代表中的每条记录,并执行必要的测试。这在练习 13.4 中有具体的应用。 + +可以抽象为下面的代码段: + +```go +var tests = []struct{ // Test table + in string + out string + +}{ + {“in1”, “exp1”}, + {“in2”, “exp2”}, + {“in3”, “exp3”}, +... +} + +func TestFunction(t *testing.T) { + for i, tt := range tests { + s := FuncToBeTested(tt.in) + if s != tt.out { + t.Errorf(“%d. %q => %q, wanted: %q”, i, tt.in, s, tt.out) + } + } +} + +``` + +如果大部分函数都可以写成这种形式,那么写一个帮助函数 verify 对实际测试会很有用: + +```go +func verify(t *testing.T, testnum int, testcase, input, output, expected string) { + if input != output { + t.Errorf(“%d. %s with input = %s: output %s != %s”, testnum, testcase, input, output, expected) + } +} + +``` + +TestFunction 则变为: + +```go + +func TestFunction(t *testing.T) { + for i, tt := range tests { + s := FuncToBeTested(tt.in) + verify(t, i, “FuncToBeTested: “, tt.in, s, tt.out) + } +} + +``` + +## 链接 + +- [目录](directory.md) +- 上一节:[测试的具体例子](13.8.md) +- 下一节:[性能调试:分析并优化 Go 程序](13.10.md) \ No newline at end of file diff --git a/eBook/directory.md b/eBook/directory.md index 8b3dfa8..dba0adc 100644 --- a/eBook/directory.md +++ b/eBook/directory.md @@ -134,6 +134,7 @@ - 13.7 [Go 中的单元测试和基准测试](13.7.md) - 13.8 [测试的具体例子](13.8.md) - 13.9 [用(测试数据)表驱动测试](13.9.md) + - 13.10 [性能调试:分析并优化 Go 程序](13.10.md) - 第14章:goroutine 与 channel - 第15章:网络、模版与网页应用