Go 语言推荐测试文件和源代码文件放在一块,测试文件以 _test.go 结尾。
test/
|--math.go
|--math_test.go
package test
func Add(a int, b int) int {
return a + b
}
package test
import "testing"
func TestAdd(t *testing.T) {
if ans := Add(2, 2); ans != 3 {
t.Errorf("期望是结果3, 但是获取值为%d", ans)
}
t.Error("t.Error")
t.Fail()
t.Error("t.Error")
//t.FailNow()
t.Log("aaaaa")
}
- 测试用例名称一般命名为 Test 加上待测试的方法名。
- 测试用的参数有且只有一个,在这里是 t *testing.T。
- *testing.T为普通测试
- *testing.B基准测试(benchmark)
- *testing.M是TestMain
- *testing.Tb为test case
testing.T
判定失败接口
Fail 失败继续
FailNow 失败终止
打印信息接口
Log 数据流 (cout 类似)
Logf format (printf 类似)
SkipNow 跳过当前测试
Skiped 检测是否跳过
综合接口产生:
Error / Errorf 报告出错继续 [ Log / Logf + Fail ]
Fatel / Fatelf 报告出错终止 [ Log / Logf + FailNow ]
Skip / Skipf 报告并跳过 [ Log / Logf + SkipNow ]
testing.B
首先 , testing.B 拥有testing.T 的全部接口。
SetBytes( i uint64) 统计内存消耗, 如果你需要的话。
SetParallelism(p int) 制定并行数目。
StartTimer / StopTimer / ResertTimer 操作计时器
testing.PB
Next() 接口 。 判断是否继续循环
三。子测试
有时候我们一次测试多个用例更方便一些,golang支持子测试,写法如下:
testing.M函数可以在测试函数执行之前做一些其他操作
func Test1(t *testing.T) {
fmt.Println("I'm test1")
}
func TestMain(m *testing.M) {
fmt.Println("I'm TestMain")
//before()
fmt.Println("程序执行之前做一些事")
m.Run()
fmt.Println("程序执行结束之后做一些事")
}
返回结果如下:
I'm TestMain
程序执行之前做一些事
=== RUN Test1
I'm test1
--- PASS: Test1 (0.00s)
PASS
程序执行结束之后做一些事
Process finished with exit code 0
五。testing.B性能测试
六。网络测试
1.httpTest
如果是使用的http标准库可以使用httptest
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func TestConn(t *testing.T) {
req := httptest.NewRequest("GET", "http://124.193.103.234:8200/homepage", nil)
w := httptest.NewRecorder()
helloHandler(w, req)
bytes, _ := ioutil.ReadAll(w.Result().Body)
if string(bytes) != "hello world" {
t.Fatal("expected hello world, but got", string(bytes))
}
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
}
2.gofight
一般实际项目中会使用gin或beego等框架,可以使用gofight来测试
https://github.com/appleboy/gofight
使用方式举例,更多可以参考github
func TestQueryString(t *testing.T) {
r := gofight.New()
r.GET("/hello").
SetQuery(gofight.H{
"a": "1",
"b": "2",
}).
Run(BasicEngine, func(r HTTPResponse, rq HTTPRequest) {
assert.Equal(t, http.StatusOK, r.Code)
})
}