add_test.go 671 B

123456789101112131415161718192021222324252627
  1. package add
  2. import "testing"
  3. func TestAdd(t *testing.T) {
  4. // 1. 定义测试表:每行是 输入a, 输入b, 期望结果want
  5. tests := []struct {
  6. a, b, want int
  7. name string // 给用例起个可读名字,失败时好定位
  8. }{
  9. {2, 3, 5, "positive"},
  10. {-1, -1, -2, "negative"},
  11. {0, 7, 7, "zero"},
  12. {0, 0, 0, "zero+zero"},
  13. {-5, 5, 0, "negative+positive"},
  14. }
  15. // 2. 遍历表格,一行就是一个子测试
  16. for _, tc := range tests {
  17. t.Run(tc.name, func(t *testing.T) { // 子测试,失败时能看到名字
  18. got := Add(tc.a, tc.b)
  19. if got != tc.want {
  20. t.Errorf("Add(%d, %d) = %d; want %d", tc.a, tc.b, got, tc.want)
  21. }
  22. })
  23. }
  24. }