Go单元测试实践
单元测试通常用来在日常开发中检查代码中存在的问题,是提升代码质量一种有效手段。在保证代码功能没有问题的同时,可以得到预期结果。Golang有许多优秀的框架支持UT,下面列举日常开发中不同框架对应的UT情况,以便后来人实践UT。
1、Goland提供的简单UT模板
用途:对其中一个函数、方法生成UT
介绍:在新手不知道如何写UT,按照什么规范去编写UT的时候,不妨采用Goland自带的模板。
tips:在Goland选中要测试的方法、函数–“gererate”–“Test for selection”,然后在// TODO: Add test cases中加入自己的测试用例数据即可。
缺点:通用性一般,适合逻辑简单的函数。
2、Convey
用途:较为好用的UT框架,断言多样,提供UT的web界面,较为常用
官方文档:link
tips:Testify: 断言库,断言功能丰富,简单易用,通常和其他框架搭配使用
code example:


1 // TestFunc
2 func CheckVal(val string) bool {
3 valList := []string{"AAA", "BBB"}
4 for index := range valList {
5 if valList[index] == val {
6 return true
7 }
8 }
9 return false
10 }
11
12
13 // Convey特点:断言函数丰富,提供UT的web界面,较为常用
14 // Convey website: https://github.com/smartystreets/goconvey/wiki/Documentation
15
16 // Testify: 断言库,多用它提供的丰富的断言功能
17 func TestCheckVal(t *testing.T) {
18 convey.Convey("TestCheckVal happy path", t, func(){
19 res := CheckVal("AAA")
20 convey.So(res, convey.ShouldBeTrue)
21 assert.True(t, res)
22 })
23
24 convey.Convey("TestCheckVal unhappy path", t, func(){
25 res := CheckVal("CCC")
26 convey.So(res, convey.ShouldBeFalse)
27 assert.False(t, res)
28 })
29 }


