GoConvey是一款針對Golang的測試框架,可以管理和運行測試用例,同時提供了豐富的斷言函數,並支持很多 Web 界面特性。
Golang雖然自帶了單元測試功能,並且在GoConvey框架誕生之前也出現了許多第三方測試框架,但沒有一個測試框架像GoConvey一樣能夠讓程序員如此簡潔優雅的編寫測試代碼
Golang雖然自帶了單元測試功能,並且在GoConvey框架誕生之前也出現了許多第三方測試框架,但沒有一個測試框架像GoConvey一樣能夠讓程序員如此簡潔優雅的編寫測試代碼
總結:
- import goconvey包時,前面加點號".",以減少冗余的代碼。凡是在測試代碼中看到Convey和So兩個方法,肯定是convey包的,不要在產品代碼中定義相同的函數名
- 測試函數的名字必須以Test開頭,而且參數類型必須為*testing.T
- Convey(string,testing.T,func{
Convey(string,func{})
Convey(string,func{})
So(實際結果,斷言函數變量,預測的結果)
}) - 每個測試用例必須使用Convey函數包裹起來,它的第一個參數為string類型的測試描述,第二個參數為測試函數的入參(類型為*testing.T),第三個參數為不接收任何參數也不返回任何值的函數(習慣使用閉包)
- Convey函數的第三個參數閉包的實現中通過So函數完成斷言判斷,它的第一個參數為實際值,第二個參數為斷言函數變量,第三個參數或者沒有(當第二個參數為類ShouldBeTrue形式的函數變量)或者有(當第二個函數為類ShouldEqual形式的函數變量)
import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestStringSliceEqual(t *testing.T) { Convey("TestStringSliceEqual", t, func() { Convey("should return true when a != nil && b != nil", func() { a := []string{"hello", "goconvey"} b := []string{"hello", "goconvey"} So(StringSliceEqual(a, b), ShouldBeTrue) }) Convey("should return true when a == nil && b == nil", func() { So(StringSliceEqual(nil, nil), ShouldBeTrue) }) Convey("should return false when a == nil && b != nil", func() { a := []string(nil) b := []string{} So(StringSliceEqual(a, b), ShouldBeFalse) }) Convey("should return false when a != nil && b != nil", func() { a := []string{"hello", "world"} b := []string{"hello", "goconvey"} So(StringSliceEqual(a, b), ShouldBeFalse) }) }) }
重點關注So斷言的使用和Convey嵌套使用。