【发布时间】:2016-02-12 07:45:12
【问题描述】:
如何为 Beego 应用编写测试用例。正如我在 Beego 网站上看到的,他们有模型测试用例,但是控制器呢?
任何可以提供帮助的框架?
【问题讨论】:
标签: unit-testing go testcase beego
如何为 Beego 应用编写测试用例。正如我在 Beego 网站上看到的,他们有模型测试用例,但是控制器呢?
任何可以提供帮助的框架?
【问题讨论】:
标签: unit-testing go testcase beego
这是一个beego示例项目。在 test 文件夹中,它显示了如何为控制器编写单元测试 https://github.com/goinggo/beego-mgo
【讨论】:
我找到了一种使用ginkgo 的方法。
测试 GET 请求:
Describe("GET /login", func() {
It("response has http code 200", func() {
request, _ := http.NewRequest("GET", "/login", nil)
response := httptest.NewRecorder()
beego.BeeApp.Handlers.ServeHTTP(response, request)
Expect(response.Code).To(Equal(http.StatusOK))
})
})
测试 POST 请求:
Describe("POST /login", func() {
Context("when passwords don't match", func() {
It("informs about error", func() {
form := url.Values{
"password": {"foobar"},
"password-confirmation": {"barfoo"},
}
body := strings.NewReader(form.Encode())
request, _ := http.NewRequest("POST", "/login", body)
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
response := httptest.NewRecorder()
beego.BeeApp.Handlers.ServeHTTP(response, request)
Expect(response.Code).To(Equal(http.StatusOK))
Expect(response.Body.String()).To(ContainSubstring("wrong passwords..."))
})
})
})
同样在BeforeSuite我需要初始化路由器并调用beego.TestBeegoInit(<APP_PATH>)
var _ = BeforeSuite(func() {
routers.Initialize() // here calling router code
beego.TestBeegoInit(AppPath())
})
【讨论】: