初学golang,使用beego做web开发,总想测试接口返回是不是预想的,但是beego的`default_test.go`这个demo只能测试非数据库连接的,一旦有数据库连接的controller就没办法测试了;提示`Handler crashed with error <Ormer.Using> unknown db alias name `default``,在models里面的init中配置了连接数据库那一套也不行,这个到底要怎么才能进行测试?如果集成sql_mock后怎么进行测试?有了解的请不吝赐教,谢谢;下面这段代码是default_test.go里面的
```go
package test
import (
"net/http"
"net/http/httptest"
"testing"
"runtime"
"path/filepath"
_ "shangpu/routers"
beego "github.com/beego/beego/v2/server/web"
. "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)
})
})
}
```
有疑问加站长微信联系(非本文作者)