Go Martini单元测试示例

huangapple go评论85阅读模式
英文:

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`)
}

总结:

  1. 使用martini.Classic()创建一个服务器。
  2. 创建一个路由到要测试的处理程序。
  3. 使用响应记录器执行它。
  4. 检查响应记录器上的结果(状态码、正文)是否符合预期。
英文:

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:

  1. Create a server with martini.Classic()
  2. Create a route to the handler you want to test
  3. Execute it against a response recorder
  4. Inspect the results (status code, body) on the response recorder are as expected.

huangapple
  • 本文由 发表于 2015年6月21日 03:24:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/30958005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定