go get github.com/smartystreets/goconvey
some_functions.go
package goconveydemo
import "errors"
func IsEqual(a, b int) bool{
return a == b
}
func IsEqualWithErr(a, b int) (bool, error){
if a > b {
return false, errors.New("over")
} else if a < b{
return false, errors.New("under")
} else{
return true, nil
}
}
goconvey_test.go
package goconveydemo
import (
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestSpec(t *testing.T) {
// Only pass t into top-level Convey calls
Convey("Given some integer with a starting value", t, func() {
x := 1
Convey("When the integer is incremented", func() {
x++
Convey("The value should be greater by one", func() {
So(x, ShouldEqual, 2)
})
})
})
}
func TestIsEqual(t *testing.T){
Convey("1 == 1", t, func() {
So(IsEqual(1, 1), ShouldBeTrue)
})
}
func TestIsEqualWithErr(t *testing.T){
Convey("IsEqualWithErr", t, func(){
Convey("2 > 1, over", func(){
ok, err := IsEqualWithErr(2, 1)
So(ok, ShouldBeFalse)
So(err, ShouldNotBeNil)
})
Convey("1 < 2, under", func(){
ok, err := IsEqualWithErr(1, 2)
So(ok, ShouldBeFalse)
So(err, ShouldNotBeNil)
})
Convey("1 = 1, equal", func(){
ok, err := IsEqualWithErr(1, 1)
So(ok, ShouldBeTrue)
So(err, ShouldBeNil)
})
})
}
_test.go
结尾的,这样在执行go test
的时候才会执行到相应的代码testing
这个包Test
开头TestXxx()
的参数是testing.T
,我们可以使用该类型来记录错误或者是测试状态func TestXxx (t *testing.T)
,Xxx
部分可以为任意的字母数字的组合,但是首字母不能是小写字母[a-z],例如Testintdiv
是错误的函数名。testing.T
的Error
, Errorf
, FailNow
, Fatal
, FatalIf
方法,说明测试不通过,调用Log
方法用来记录测试的信息。
当gotest运行具体文件时,需要把依赖的文件一起打出来,否则会报错。
如本例
go test -v goconvey_test.go
//输出
# command-line-arguments [command-line-arguments.test]
./goconvey_test.go:25:6: undefined: IsEqual
./goconvey_test.go:32:15: undefined: IsEqualWithErr
./goconvey_test.go:38:15: undefined: IsEqualWithErr
./goconvey_test.go:44:15: undefined: IsEqualWithErr
FAIL command-line-arguments [build failed]
正确写法如下
go test -v goconvey_test.go some_functions.go
//输出
=== RUN TestSpec
Given some integer with a starting value
When the integer is incremented
The value should be greater by one ✔
1 total assertion
--- PASS: TestSpec (0.00s)
=== RUN TestIsEqual
1 == 1 ✔
2 total assertions
--- PASS: TestIsEqual (0.00s)
=== RUN TestIsEqualWithErr
IsEqualWithErr
2 > 1, over ✔✔
1 < 2, under ✔✔
1 = 1, equal ✔✔
8 total assertions
--- PASS: TestIsEqualWithErr (0.00s)
PASS
ok command-line-arguments 0.006s