go 單元測試testify

 

testify介紹

testify用go實現的一個assert風格的測試框架,這個包提供了我們需要的斷言的功能,提供了非常豐富的斷言方法。

提供了測試suite、斷言、mock三種功能。

官方文檔:https://godoc.org/github.com/stretchr/testify

安裝:

go get -u -v github.com/stretchr/testify

testify斷言

有兩種斷言方式,區別是require的斷言失敗會直接導致程序結束,而assert雖然也標記爲此case失敗,但程序不會退出,而是繼續往下執行。

  1. assert
  2. require
import (
    "github.com/stretchr/testify/assert"
    "testing"
)

//單元測試函數
func TestAddNum(t *testing.T) {
    result :=  addNum(100)
    assert.Equal(t, 5050, result)
}

功能代碼如下:

func addNum(n int) (result int) {
    for i := 0; i <= n; i++ {
        result = result + i
    }
    return result 
} 

更多斷言類型:

https://godoc.org/github.com/stretchr/testify/assert

https://godoc.org/github.com/stretchr/testify/require

testify suite

package untest

// Basic imports
import (
    "testing"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/suite"
)

type ExampleTestSuite struct {
    suite.Suite
    VariableThatShouldStartAtFive int
}

// 每個測試用例執行前都會調用
func (suite *ExampleTestSuite) SetupTest() {
    suite.VariableThatShouldStartAtFive = 5
}

//一個測試用例
func (suite *ExampleTestSuite) TestExample() {
    assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
    suite.Equal(5, suite.VariableThatShouldStartAtFive)
}

// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestExampleTestSuite(t *testing.T) {
    suite.Run(t, new(ExampleTestSuite))
}

// 每個測試用例執行後都會調用
func (suite *ExampleTestSuite) TearDownTest() {

}

Table Driven Test

通過構造結構體切片進行table driven test,這裏傳入常規參數的情況,代碼實現如下:

func TestSqrt(t *testing.T) {
  testcases := []struct {
    desc   string
    input  float64
    expect float64
  }{
    {
      desc:   "zero",
      input:  0,
      expect: 0,
    },
    {
      desc:   "one",
      input:  1,
      expect: 1,
    },
    {
      desc: "a very small rational number",
      input: 0.00000000000000000000000001,
      expect: 0.0,
    },
    {
      desc:   "rational number result: 2.56",
      input:  2.56,
      expect: 1.6,
    },
    {
      desc:   "irrational number result: 2",
      input:  2,
      expect: 1.414213562,
    },
  }

  for _, ts := range testcases {
    got := Sqrt(ts.input)
    erro := got - ts.expect
    require.True(t, erro < 0.000000001 && erro > -0.000000001, ts.desc)
  }
}

功能代碼如下:

// Sqrt calculate the square root of a non-negative float64 
// number with max error of 10^-9. For simplicity, we don't 
// discard the part with is smaller than 10^-9.
func Sqrt(x float64) float64 {
  if x < 0 {
    panic("cannot be negative")
  }

  if x == 0 {
    return 0
  }

  a := x / 2
  b := (a + 2) / 2
  erro := a - b
  for erro >= 0.000000001 || erro <= -0.000000001 {
    a = b
    b = (b + x/b) / 2
    erro = a - b
  }

  return b
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章