main_test.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package main
  2. import "testing"
  3. // 1. 最基础测试:准备输入 -> 调用函数 -> 比较实际值与期望值。
  4. // 测试函数以 Test 开头,接收 *testing.T,没有返回值。
  5. func TestAdd(t *testing.T) {
  6. got := add(2, 3) // got:实际得到的结果,是普通变量名。
  7. want := 5 // want:期望结果,同样不是关键字。
  8. if got != want {
  9. // Fatalf:记录失败信息、标记失败,并停止当前测试。
  10. t.Fatalf("add(2, 3):实际=%d,期望=%d", got, want)
  11. }
  12. // Logf 只记录日志,不会把测试标记为失败;通过时用 -v 查看日志。
  13. t.Logf("检查通过:实际=%d,期望=%d", got, want)
  14. }
  15. // 2. 表驱动测试:把多组输入和期望结果放到结构体切片里。
  16. func TestAddTable(t *testing.T) {
  17. tests := []struct {
  18. name string
  19. a int
  20. b int
  21. want int
  22. }{
  23. {name: "positive", a: 2, b: 3, want: 5},
  24. {name: "zero", a: 0, b: 0, want: 0},
  25. {name: "negative", a: -2, b: -3, want: -5},
  26. {name: "mixed", a: -2, b: 3, want: 1},
  27. }
  28. for _, tt := range tests {
  29. // Run 的参数:子测试名称、执行子测试的函数值。
  30. // 匿名函数没有末尾的 (),由测试框架负责调用。
  31. t.Run(tt.name, func(t *testing.T) {
  32. got := add(tt.a, tt.b)
  33. if got != tt.want {
  34. // Errorf:记录并标记失败,但继续执行当前测试后面的代码。
  35. t.Errorf("add(%d, %d):实际=%d,期望=%d", tt.a, tt.b, got, tt.want)
  36. }
  37. })
  38. }
  39. }
  40. // 3. 测试有 error 返回值的函数:成功路径和失败路径都要覆盖。
  41. func TestParseScore(t *testing.T) {
  42. tests := []struct {
  43. name string
  44. input string
  45. want int
  46. wantErr bool
  47. }{
  48. {name: "normal", input: "85", want: 85, wantErr: false},
  49. {name: "lower_bound", input: "0", want: 0, wantErr: false},
  50. {name: "upper_bound", input: "100", want: 100, wantErr: false},
  51. {name: "below_range", input: "-1", wantErr: true},
  52. {name: "above_range", input: "101", wantErr: true},
  53. {name: "invalid_text", input: "abc", wantErr: true},
  54. {name: "empty", input: "", wantErr: true},
  55. {name: "decimal", input: "80.5", wantErr: true},
  56. }
  57. for _, tt := range tests {
  58. t.Run(tt.name, func(t *testing.T) {
  59. got, err := parseScore(tt.input)
  60. hasErr := err != nil
  61. if hasErr != tt.wantErr {
  62. t.Fatalf("parseScore(%q):错误=%v,期望发生错误=%t", tt.input, err, tt.wantErr)
  63. }
  64. if tt.wantErr {
  65. return // 已确认发生预期错误,本用例不再检查无效结果。
  66. }
  67. if got != tt.want {
  68. t.Errorf("parseScore(%q):实际=%d,期望=%d", tt.input, got, tt.want)
  69. }
  70. })
  71. }
  72. }