go语言的测试采用的框架如下:
在前面进行了beego框架的搭建,beego自带的有test,但是通过IDE(如VScode)不能直接运行测试用例,如下:
1、可以通过在测试用例里加main来调用测试用例
2、直接在终端进行运行,如在test目录下运行go test -v可以输出test目录下所以用例运行结果及显示详细的流程
也可以运行某一个测试用例:
$ go test helloworld_test.go
ok command-line-arguments 0.003s
$ go test -v helloworld_test.go
=== RUN TestHelloWorld
--- PASS: TestHelloWorld (0.00s)
helloworld_test.go:8: hello world
PASS
ok command-line-arguments 0.004s
goConvey是作为外层框架进行单元测试管理。
$ go get github.com/smartystreets/goconvey
go get下载不下来的可以通过https://github.com/smartystreets/goconvey 下载zip,然后解压到$ GOPATH/src/github.com/smartystreets/goconvey go clean -r -i 和 go install -v 安装,如果在$GOPATH/bin 下生成goconvey二进制文件,说明安装成功
package test
import (
"net/http"
"net/http/httptest"
"testing"
"runtime"
"path/filepath"
_ "myproject/routers"
"github.com/astaxie/beego"
. "github.com/smartystreets/goconvey/convey"
)
func init() {
_, file, _, _ := runtime.Caller(0)
apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".." + string(filepath.Separator))))
beego.TestBeegoInit(apppath)
}
// TestBeego is a sample to run an endpoint test
func TestBeego(t *testing.T) {
r, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
beego.BeeApp.Handlers.ServeHTTP(w, r)
beego.Trace("testing", "TestBeego", "Code[%d]\n%s", w.Code, w.Body.String())
Convey("Subject: Test Station Endpoint\n", t, func() {
Convey("Status Code Should Be 200", func() {
So(w.Code, ShouldEqual, 200)
})
Convey("The Result Should Not Be Empty", func() {
So(w.Body.Len(), ShouldBeGreaterThan, 0)
})
})
}
在$GOPATH/bin/下执行./goconvey(也可直接点击goconvey二进制文件,不过要手动关闭8080),一开始会报错,浏览器也是404,后来在提示下添加目录,可以正常浏览了
但是此时浏览器没有任何test运行,上面的文件目录显示是/usr/lib/go/bin,然后把目录修改为/usr/lib/go/src/github.com/smartystreets/goconvey,最后刷新一下就可以显示测试用例了。
如果想看自己的项目,修改为自己项目目录即可。
go get github.com/bouk/monkey 或者 https://github.com/bouk/monkey下载解压到$ GOPATH/src/github.com/bouk/monkey(无需生成二进制文件)
直接在测试用例中导入monkey调用相关函数就可,可参考文档 https://github.com/bouk/monkey
代码测试用例的覆盖率有三种方式:
root@ZTE:/usr/lib/go/src/myproject/tests# go test -cover
PASS
coverage: 0.0% of statements
ok _/usr/lib/go/src/myproject/tests 0.021s
https://github.com/philwinder/gocoverage下载gocoverage组件,解压到$ GOPATH/src/github.com/ go clean -r -i 和 go install -v 安装,如果在$GOPATH/bin 下生成gocoverage二进制文件,说明安装成功。然后直接
gocoverage [flags...] rootpath filterpath1 ... filterpathn