Test-Driven Development - Go (3)
go golang TDD Test-Driven Development
上一篇我們用的一個範例來完成整個 TDD 的 Flow
這一篇我們要調整一下 Test Case 在 golang 上撰寫方式
上一篇我們在每次添加一個 Test Case 都建立一個新的 function
你可以看一下底下的 Code 內容都是相像的
  func TestBuyOneBook(t *testing.T) {
    price := calculatePrice([]int{1}) // 呼叫 func
    if price != 8 { // 判斷回傳
      t.Fatal("price should be 8, but got", price)
    }
  }
  func TestBuyTwoDifferentBook(t *testing.T) {
    price := calculatePrice([]int{1, 2}) // 呼叫 func
    if price != 15.2 { // 判斷回傳
      t.Fatal("price should be 15.2, but got", price)
    }
  }
同一個 func 的 大量 test 是可以有另外一種比較方便的寫法
可以把 測試名稱 參數 回傳值 變成一個 struct
然後放在 array 跑 for 迴圈 進行每一個測試
好處會是要增加一個 test case 只要添加進 array 就好
底下是根據我們上一篇的 func calculatePrice 的另一種測試 case 寫法
  func Test_calculatePrice(t *testing.T) {
    type args struct { // 參數 struct
      books []int
    }
    tests := []struct {
      name string // 測試名稱,會在有錯誤的時候顯示
      args args // 參數
      want float32 // 期待得到的回傳值
    }{
      {
        name: "One Book",
        args: args{books: []int{1}},
        want: 8,
      },
      {
        name: "two different book",
        args: args{books: []int{1, 2}},
        want: 2 * 8 * 0.95,
      },
    }
    for _, tt := range tests {
      t.Run(tt.name, func(t *testing.T) {
        if got := calculatePrice(tt.args.books); got != tt.want {
          t.Errorf("calculatePrice() should got %v, but got %v", tt.want, got)
        }
      })
    }
  }
打完收工