-
下载convey库:
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)
})
})
}
-
运行$GOPATH/bin目录下生成的goconvey程序,打开http://localhost:8080

-
运行go test -v

-
PS:golang test单元测试规范
- 文件名必须是
_test.go结尾的,这样在执行go test的时候才会执行到相应的代码 - 你必须import
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
GoConvey单元测试实战
本文详细介绍如何使用GoConvey库进行Go语言的单元测试,包括下载库、编写测试函数和测试用例,以及运行测试的过程。文章强调了测试文件命名、测试函数格式等规范,并展示了如何使用Convey进行断言。
1586

被折叠的 条评论
为什么被折叠?



