mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 00:43:26 +08:00
13.0-13.10
This commit is contained in:
@@ -15,7 +15,7 @@ var tests = []struct{ // Test table
|
||||
{“in1”, “exp1”},
|
||||
{“in2”, “exp2”},
|
||||
{“in3”, “exp3”},
|
||||
...
|
||||
...
|
||||
}
|
||||
|
||||
func TestFunction(t *testing.T) {
|
||||
@@ -23,10 +23,9 @@ func TestFunction(t *testing.T) {
|
||||
s := FuncToBeTested(tt.in)
|
||||
if s != tt.out {
|
||||
t.Errorf(“%d. %q => %q, wanted: %q”, i, tt.in, s, tt.out)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
如果大部分函数都可以写成这种形式,那么写一个帮助函数 verify 对实际测试会很有帮助:
|
||||
@@ -35,26 +34,23 @@ func TestFunction(t *testing.T) {
|
||||
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)
|
||||
- 下一节:[性能调试:分析并优化 Go 程序](13.10.md)
|
||||
|
Reference in New Issue
Block a user