如何为 beego 应用编写测试用例?

如何为 Beego 应用编写测试用例。正如我在 Beego 网站上看到的,他们有模型测试用例,但是控制器呢?

任何可以提供帮助的框架?


沧海一幻觉
浏览 310回答 2
2回答

慕虎7371278

我找到了一种使用ginkgo 的方法。测试GET请求:Describe("GET /login", func() {&nbsp; &nbsp; It("response has http code 200", func() {&nbsp; &nbsp; &nbsp; &nbsp; request, _ := http.NewRequest("GET", "/login", nil)&nbsp; &nbsp; &nbsp; &nbsp; response := httptest.NewRecorder()&nbsp; &nbsp; &nbsp; &nbsp; beego.BeeApp.Handlers.ServeHTTP(response, request)&nbsp; &nbsp; &nbsp; &nbsp; Expect(response.Code).To(Equal(http.StatusOK))&nbsp; &nbsp; })})测试POST请求:Describe("POST /login", func() {&nbsp; &nbsp; Context("when passwords don't match", func() {&nbsp; &nbsp; &nbsp; &nbsp; It("informs about error", func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; form := url.Values{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "password": {"foobar"},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "password-confirmation": {"barfoo"},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; body := strings.NewReader(form.Encode())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; request, _ := http.NewRequest("POST", "/login", body)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; request.Header.Add("Content-Type", "application/x-www-form-urlencoded")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response := httptest.NewRecorder()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; beego.BeeApp.Handlers.ServeHTTP(response, request)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Expect(response.Code).To(Equal(http.StatusOK))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Expect(response.Body.String()).To(ContainSubstring("wrong passwords..."))&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; })})同样在BeforeSuite我需要初始化路由器和调用beego.TestBeegoInit(<APP_PATH>)var _ = BeforeSuite(func() {&nbsp; &nbsp; routers.Initialize() // here calling router code&nbsp; &nbsp; beego.TestBeegoInit(AppPath())})

暮色呼如

这是一个 beego 示例项目。在 test 文件夹中,它展示了如何为控制器编写单元测试&nbsp;https://github.com/goinggo/beego-mgo
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go