英文:
How to write test cases for beego app?
问题
如何为Beego应用编写测试用例?根据我在Beego网站上的了解,他们有模型测试用例,但控制器呢?
有没有可以帮助的框架?
英文:
How to approach writing test cases for Beego app. As i can see on Beego website, they have model test case but what about controllers?
Any Framework which can help?
答案1
得分: 2
我找到了一种使用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() // 在这里调用路由代码
beego.TestBeegoInit(AppPath())
})
英文:
I've found one approach using ginkgo.
Testing a GET request:
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))
})
})
Testing a POST request:
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..."))
})
})
})
Also in the BeforeSuite
I needed to initialize the routers and calling beego.TestBeegoInit(<APP_PATH>)
var _ = BeforeSuite(func() {
routers.Initialize() // here calling router code
beego.TestBeegoInit(AppPath())
})
答案2
得分: 1
这是一个beego示例项目。在测试文件夹中,展示了如何为控制器编写单元测试。
https://github.com/goinggo/beego-mgo
英文:
This is a beego sample project. In the test folder, it shows how to write unit test for controllers
https://github.com/goinggo/beego-mgo
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论