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失败,但程序不会退出,而是继续往下执行。
- assert
- 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 }