1.golang的测试框架stretchr/testify
1.stretchr/testify/assert
assert库是这样的一个库,它有一系列函数来适应各种各样不同的场景需求,下面是一个简单的判断值是否符合预期的demo:
func TestFunc1(t *testing.T) {
name := "Bob"
age := 10
assert.Equal(t, "Bob", name, "name should equal to Bob")
assert.Equal(t, 10, age, "age should equal to 10")
}
命令行输入go test -v,对应的结果是PASS。我们尝试将第二个assert.Equal的10改成11,观察效果:
![cf0734d4a80919df6de2e1f47fb193c5.png](https://img-blog.csdnimg.cn/img_convert/cf0734d4a80919df6de2e1f47fb193c5.png)
可以看到,这个时候报错会报错误的行数、错误的原因、测试函数及所带的Messages。而有些assert库的断言函数基本都是这样的原型:
func AssertFunc(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
那我们很自然地就能得出这些参数的含义:
参数名含义
t TestingT 当前测试函数的t *testing.T
expected interface{} 预期的结果
actual interface{} 实际计算得到的结果
msgAndArgs ...interface{} 形如fmt.Printf中的格式化输出字符串
一些常用的assert库断言函数如下:
断言函数作用
Equal/NotEqual 判断expected与actual相等/不相等
Nil/NotNil 判断object为nil/不为nil
Empty/NotEmpty 判断object为void/不为void
NoError/Error 判断err无值/有值
Zero/NotZero 判断i为0/不为0
True/False 判断value为true/false
Len 判断object长度是否为length
Contains/NotContains 判断s在/不在contains中
Subset/NotSubset 判断subset是/不是list的子集
FileExists 判断path所示的文件是否存在
DirExists 判断path所示的文件夹是否存在
2.stretchr/testify/require
这个库和assert库几乎是一致的,但是require遇到FAIL的例子会马上停下来,不再测试后面的测试用例。下面是一个使用assert库和require库分别测试错误用例的例子:
func TestFunc1(t *testing.T) {
name := "Bob"
age := 10
kilo := 1
assert.Equal(t, "Bob", name, "name should equal to Bob")
assert.Equal(t, 10, age, "age should equal to 10")
assert.Zero(t, kilo, "kilo should be zero")
}
执行测试,可以发现就算14行的断言并不返回true,15行的断言也会被继续执行:
![5c406767f603793a175ebe27be55ce8d.png](https://img-blog.csdnimg.cn/img_convert/5c406767f603793a175ebe27be55ce8d.png)
我们把所有的assert都换成require,再做一下测试:
![c4284c396168aad7befe5b85500e9135.png](https://img-blog.csdnimg.cn/img_convert/c4284c396168aad7befe5b85500e9135.png)
可以发现当第二个测试没通过后,第三个测试就不会被执行了(相当于执行了一次t.Errorf)。
2.测试框架GoConvey
GoConvey是一种可以组织测试用例间的逻辑关系的一种测试框架,通过使用GoConvey提供的嵌套功能,可以把测试用例分在不同的测试要求下,从而实现一种直观的、可以看到覆盖范围的测试用例组合。
2.1单个测试用例下使用GoConvey
我们先来探究单个测试用例下怎么使用GoConvey,一个demo如图:
// IsOdd 判断给定数字是否为奇数
func IsOdd(n int) bool {
return n%2 != 0
}
func TestIsOdd(t *testing.T) {
Convey("TestIsOdd should return true when n is odd number", t, func() {
n := 2
So(IsOdd(n), ShouldBeTrue)
})
}
我们可以看到,Convey的第一个参数指的是该测试的名字,第二个参数是testing.T的指针,第三个参数是一个闭包,用于测试,其中So是断言函数,ShouldBeTrue代表着只有true的情况下这个测试用例才能通过。
执行go test -v,可以得到结果:
![32c5be92e98b94a485dcce65b7aeff91.png](https://img-blog.csdnimg.cn/img_convert/32c5be92e98b94a485dcce65b7aeff91.png)
如果故意改为不过,报错就是这样的:
![917e29a5004479828346dfbc9b2dc322.png](https://img-blog.csdnimg.cn/img_convert/917e29a5004479828346dfbc9b2dc322.png)
通过的样例会在测试说明后接一个.,而不过的样例则会借一个x,并且指出错误函数和错误原因。
2.2多个独立测试用例下使用GoConvey
如果我需要做多个测试,而这些测