天天看點

golang壓力測試和性能測試

package gotest

import (
  "errors"
)

func Division(a, b float64) (float64, error) {
  if b == 0 {
    return 0, errors.New("除數不能為0")
  }

  return a / b, nil
}      

go.test.go 檔案

package gotest
import (
  "testing"
)
func Test_Division_1(t *testing.T) {
  if i, e := Division(6, 2); i != 3 || e != nil { //try a unit test on function
    t.Error("除法函數測試沒通過") // 如果不是如預期的那麼就報錯
  } else {
    t.Log("第一個測試通過了") //記錄一些你期望記錄的資訊
  }
}

func Test_Division_2(t *testing.T) {
  //t.Error("就是不通過")
  if _, e := Division(6, 0); e == nil { //try a unit test on function
    t.Error("Division did not work as expected.") // 如果不是如預期的那麼就報錯
  } else {
    t.Log("one test passed.", e) //記錄一些你期望記錄的資訊
  }
}      

gotest_test.go檔案

package gotest

import (
  "testing"
)

func Benchmark_Division(b *testing.B) {
  for i := 0; i < b.N; i++ { //use b.N for looping
    Division(4, 5)
  }
}

func Benchmark_TimeConsumingFunction(b *testing.B) {
  b.StopTimer() //調用該函數停止壓力測試的時間計數

  //做一些初始化的工作,例如讀取檔案資料,資料庫連接配接之類的,
  //這樣這些時間不影響我們測試函數本身的性能

  b.StartTimer() //重新開始時間
  for i := 0; i < b.N; i++ {
    Division(4, 5)
  }
}