如何对 Google App Engine Go HTTP 处理程序进行单元测试?

Google App Engine Go SDK 1.8.6 版支持本地单元测试。该appengine/aetest包允许我创建一个Context单元测试。

我如何使用它net/http/httptest来测试我的 HTTP 处理程序?


临摹微笑
浏览 204回答 2
2回答

富国沪深

如果您不反对使用Martini,则依赖注入是解决问题的好方法。以下是设置测试的方法(使用Ginkgo):var _ = Describe("Items", func() {    var (        m *martini.ClassicMartini    )    BeforeEach(func() {        m = martini.Classic()        // injects app engine context into requests        m.Use(func(c martini.Context, req *http.Request) {             con, _ := aetest.NewContext(nil)             c.MapTo(con, (*appengine.Context)(nil))        })        m.Get("/items", func(c martini.Context){             // code you want to test        })    })    It("should get items", func() {        recorder := httptest.NewRecorder()        r, _ := http.NewRequest("GET", "/items", nil)        m.ServeHTTP(recorder, r) // martini server used        Expect(recorder.Code).To(Equal(200))    })})在生产中,实际的上下文将被注入:m.Use(func(c martini.Context, req *http.Request) {    c.MapTo(appengine.NewContext(req), (*appengine.Context)(nil))})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go