golang的測試架構stretchr/testify
$ export GOPATH=~/go$ go get github.com/stretchr/testify
然後在你的GOPATH目錄下面就可以看到
$ ls ${GOPATH}/src/github.com/stretchr/testifyassert _codegen doc.go Gopkg.lock Gopkg.toml http LICENSE mock package_test.go README.md require suite vendor
我主要用兩個包
- assert package
- require package
他們的唯一差別就是require的函數會直接導致case結束,而assert雖然也標記為case失敗,但case不會退出,而是繼續往下執行。看一個例子:
例子1:使用assert
package mainimport ( "testing" "github.com/stretchr/testify/assert" )func TestCase1(t *testing.T) { name := "Bob" age := 10 assert.Equal(t, "bob", name) assert.Equal(t, 20, age)}
執行:
$ go test --- FAIL: TestCase1 (0.00s) assertions.go:254: Error Trace: main_test.go:13 Error: Not equal: expected: "bob" actual : "Bob" Test: TestCase1 assertions.go:254: Error Trace: main_test.go:14 Error: Not equal: expected: 20 actual : 10 Test: TestCase1FAILexit status 1FAIL testUT 0.009s
在這個例子中我們使用的是assert,可以看到兩個assert.Equal()指令都被執行了。
例子2:使用require
package mainimport ( "testing" "github.com/stretchr/testify/require")func TestCase1(t *testing.T) { name := "Bob" age := 10 require.Equal(t, "bob", name) require.Equal(t, 20, age)}
執行:
$ go test--- FAIL: TestCase1 (0.00s) assertions.go:254: Error Trace: main_test.go:12 Error: Not equal: expected: "bob" actual : "Bob" Test: TestCase1FAILexit status 1FAIL testUT 0.007s
而在這個例子中我們使用的是require,可以看到只有第一個require.Equal()指令被執行了,第二個require.Equal()沒有被執行。
常用的stretchr/testify架構函數:
func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) boolfunc NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) boolfunc Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) boolfunc NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) boolfunc Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) boolfunc NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) boolfunc NoError(t TestingT, err error, msgAndArgs ...interface{}) boolfunc Error(t TestingT, err error, msgAndArgs ...interface{}) boolfunc Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) boolfunc NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) boolfunc True(t TestingT, value bool, msgAndArgs ...interface{}) boolfunc False(t TestingT, value bool, msgAndArgs ...interface{}) boolfunc Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) boolfunc NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) boolfunc NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) boolfunc Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool)func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool)func FileExists(t TestingT, path string, msgAndArgs ...interface{}) boolfunc DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool
官方連結:
https://github.com/stretchr/testify