13.9 用(测试数据)表驱动测试

编写测试代码时,一个较好的办法是把测试的输入数据和期望的结果写在一起组成一个数据表:表中的每条记录都是一个含有输入和期望值的完整测试用例,有时还可以结合像测试名字这样的额外信息来让测试输出更多的信息。

实际测试时简单迭代表中的每条记录,并执行必要的测试。这在练习 13.4 中有具体的应用。

可以抽象为下面的代码段:

  1. var tests = []struct{ // Test table
  2. in string
  3. out string
  4. }{
  5. {"in1", "exp1"},
  6. {"in2", "exp2"},
  7. {"in3", "exp3"},
  8. ...
  9. }
  10. func TestFunction(t *testing.T) {
  11. for i, tt := range tests {
  12. s := FuncToBeTested(tt.in)
  13. if s != tt.out {
  14. t.Errorf("%d. %q => %q, wanted: %q", i, tt.in, s, tt.out)
  15. }
  16. }
  17. }

如果大部分函数都可以写成这种形式,那么写一个帮助函数 verify() 对实际测试会很有帮助:

  1. func verify(t *testing.T, testnum int, testcase, input, output, expected string) {
  2. if expected != output {
  3. t.Errorf("%d. %s with input = %s: output %s != %s", testnum, testcase, input, output, expected)
  4. }
  5. }

TestFunction() 则变为:

  1. func TestFunction(t *testing.T) {
  2. for i, tt := range tests {
  3. s := FuncToBeTested(tt.in)
  4. verify(t, i, "FuncToBeTested: ", tt.in, s, tt.out)
  5. }
  6. }

链接