英文:
Go Martini Unit Test Example
问题
我很新手Go语言,想知道有没有关于如何测试Go Martini的处理程序代码的约定/标准?提前感谢你!
英文:
I'm very new to Go and was wondering is there any convention/standard with examples on how to test Go Martini's Handler code?
Thanking you in advance!
答案1
得分: 3
martini-contrib库中有很多值得一看的现有代码:https://github.com/martini-contrib/secure/blob/master/secure_test.go
例如:
func Test_No_Config(t *testing.T) {
m := martini.Classic()
m.Use(Secure(Options{
// 这里没有配置项
}))
m.Get("/foo", func() string {
return "bar"
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
m.ServeHTTP(res, req)
expect(t, res.Code, http.StatusOK)
expect(t, res.Body.String(), `bar`)
}
总结:
- 使用
martini.Classic()
创建一个服务器。 - 创建一个路由到要测试的处理程序。
- 使用响应记录器执行它。
- 检查响应记录器上的结果(状态码、正文)是否符合预期。
英文:
The martini-contrib library has a lot of existing code worth looking at: https://github.com/martini-contrib/secure/blob/master/secure_test.go
e.g.
func Test_No_Config(t *testing.T) {
m := martini.Classic()
m.Use(Secure(Options{
// nothing here to configure
}))
m.Get("/foo", func() string {
return "bar"
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
m.ServeHTTP(res, req)
expect(t, res.Code, http.StatusOK)
expect(t, res.Body.String(), `bar`)
}
To sum:
- Create a server with
martini.Classic()
- Create a route to the handler you want to test
- Execute it against a response recorder
- Inspect the results (status code, body) on the response recorder are as expected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论