为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
临摹微笑 2021-06-30 15:54:32
Google App Engine Go SDK 1.8.6 版支持本地单元测试。该appengine/aetest包允许我创建一个Context单元测试。我如何使用它net/http/httptest来测试我的 HTTP 处理程序?
查看完整描述

2 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

如果您不反对使用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))

})


查看完整回答
反对 回复 2021-07-05
  • 2 回答
  • 0 关注
  • 203 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信