GoConvey是一个非常非常好用的Go测试框架,它直接与go test集成,提供了很多丰富的断言函数,能够在终端输出可读的彩色测试结果,并且还支持全自动的Web UI。
安装
go get github.com/smartystreets/goconvey
示例
下面是一个goconvey的测试用例写法样例:
import (
"testing"
c "github.com/smartystreets/goconvey/convey"
)
func Test_XXXX(t *testing.T) {
c.Convey("step1 ...", t, func() {
c.Convey("step2 ...", func() {
c.Convey("step3 ...", func() {
c.So(1, c.ShouldEqual, 1)
})
})
})
}
运行测试用例:

断言方法
GoConvey为我们提供了很多种类断言方法。
一般等价类
So(thing1, ShouldEqual, thing2)
So(thing1, ShouldNotEqual, thing2)
So(thing1, ShouldResemble, thing2)
So(thing1, ShouldNotResemble, thing2)
So(thing1, ShouldPointTo, thing2)
So(thing1, ShouldNotPointTo, thing2)
So(thing1, ShouldBeNil)
So(thing1, ShouldNotBeNil)
So(thing1, ShouldBeTrue)
So(thing1, ShouldBeFalse)
So(thing1, ShouldBeZeroValue)
数字数量比较类
So(1, ShouldBeGreaterThan, 0)
So(1, ShouldBeGreaterThanOrEqualTo, 0)
So(1, ShouldBeLessThan, 2)
So(1, ShouldBeLessThanOrEqualTo, 2)
So(1.1, ShouldBeBetween, 0.5, 2.2)
So(1.1, ShouldNotBeBetween, 2, 3)
So(1.1, ShouldBeBetweenOrEqual, .9, 1.1)
So(1.1, ShouldNotBeBetweenOrEqual, 1000, 2000)
So(1.0, ShouldAlmostEqual, 0.99999999, .0001)
So(1.0, ShouldNotAlmostEqual, 0.9, .0001)
包含类
So([]int{1, 2, 3}, ShouldContain, 2)
So([]int{2, 4, 6}, ShouldNotContain, 5)
So(4, ShouldBeIn, ...[]int{2, 4, 6})
So(4, ShouldNotBeIn, ...[]int{1, 3, 5})
So([]int{}, ShouldBeEmpty)
So([]int{1}, ShouldNotBeEmpty)
So(map[string]string{"a": "b"}, ShouldContainKey, "a")
So(map[string]string{"a": "b"}, ShouldNotContainKey, "b")
So(map[string]string{"a": "b"}, ShouldNotBeEmpty)
So(map[string]string{}, ShouldBeEmpty)
So(map[string]string{"a": "b"}, ShouldHaveLength, 1)
字符串类
So("qwe", ShouldStartWith, "qw")
So("qwe", ShouldNotStartWith, "as")
So("qwe", ShouldEndWith, "we")
So("qwe", ShouldNotEndWith, "sd")
So("qwe", ShouldContainSubstring, "w")
So("qwe", ShouldNotContainSubstring, "ff")
So("qwe", ShouldBeBlank)
So("qwe", ShouldNotBeBlank)
panic类
So(func(), ShouldPanic)
So(func(), ShouldNotPanic)
So(func(), ShouldPanicWith, "")
So(func(), ShouldNotPanicWith, "")
类型检查类
So(1, ShouldHaveSameTypeAs, 0)
So(1, ShouldNotHaveSameTypeAs, "qwe")
时间和时间间隔类
So(time.Now(), ShouldHappenBefore, time.Now())
So(time.Now(), ShouldHappenOnOrBefore, time.Now())
So(time.Now(), ShouldHappenAfter, time.Now())
So(time.Now(), ShouldHappenOnOrAfter, time.Now())
So(time.Now(), ShouldHappenBetween, time.Now(), time.Now())
So(time.Now(), ShouldHappenOnOrBetween, time.Now(), time.Now())
So(time.Now(), ShouldNotHappenOnOrBetween, time.Now(), time.Now())
So(time.Now(), ShouldHappenWithin, duration, time.Now())
So(time.Now(), ShouldNotHappenWithin, duration, time.Now())
WebUI
直接运用命令:goconvey,即可通过本机地址访问UI界面:http://localhost:8080/

总结
本文介绍了 Go 语言非常好用且强大的第三方库 GoConvey,然后进行下载和安装,最后使用了一个简单样例描述了一个完整的 GoConvey 使用流程,该测试库提供了更多的断言方法,可以在实际开发过程中进行运用。通过运行 goconvey 命令,可以在本地运行一个强大 Web 图形界面,建议读者将 goconvey 配合内置的 testing 使用,以提高开发效率。