返回介绍

End To End Testing

发布于 2025-02-25 22:26:27 字数 1548 浏览 0 评论 0 收藏 0

End to end allows us to test applications through the whole request cycle. Where unit testing is meant to just test a particular function, end to end tests will run the middleware, router, and other that a request my pass through.

package main

import (
  "fmt"
  "net/http"

  "github.com/codegangsta/negroni"
  "github.com/julienschmidt/httprouter"
)

func HelloWorld(res http.ResponseWriter, req *http.Request, p httprouter.Params) {
  fmt.Fprint(res, "Hello World")
}

func App() http.Handler {
  n := negroni.Classic()

  m := func(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
    fmt.Fprint(res, "Before...")
    next(res, req)
    fmt.Fprint(res, "...After")
  }
  n.Use(negroni.HandlerFunc(m))

  r := httprouter.New()

  r.GET("/", HelloWorld)
  n.UseHandler(r)
  return n
}

func main() {
  http.ListenAndServe(":3000", App())
}

This is the test file. It should be placed in the same directory as your application and name main_test.go .

package main

import (
  "io/ioutil"
  "net/http"
  "net/http/httptest"
  "testing"
)

func Test_App(t *testing.T) {
  ts := httptest.NewServer(App())
  defer ts.Close()

  res, err := http.Get(ts.URL)
  if err != nil {
    t.Fatal(err)
  }

  body, err := ioutil.ReadAll(res.Body)
  res.Body.Close()

  if err != nil {
    t.Fatal(err)
  }

  exp := "Before...Hello World...After"

  if exp != string(body) {
    t.Fatalf("Expected %s got %s", exp, body)
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文