End To End Testing

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.

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/codegangsta/negroni"
  6. "github.com/julienschmidt/httprouter"
  7. )
  8. func HelloWorld(res http.ResponseWriter, req *http.Request, p httprouter.Params) {
  9. fmt.Fprint(res, "Hello World")
  10. }
  11. func App() http.Handler {
  12. n := negroni.Classic()
  13. m := func(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
  14. fmt.Fprint(res, "Before...")
  15. next(res, req)
  16. fmt.Fprint(res, "...After")
  17. }
  18. n.Use(negroni.HandlerFunc(m))
  19. r := httprouter.New()
  20. r.GET("/", HelloWorld)
  21. n.UseHandler(r)
  22. return n
  23. }
  24. func main() {
  25. http.ListenAndServe(":3000", App())
  26. }

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

  1. package main
  2. import (
  3. "io/ioutil"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. )
  8. func Test_App(t *testing.T) {
  9. ts := httptest.NewServer(App())
  10. defer ts.Close()
  11. res, err := http.Get(ts.URL)
  12. if err != nil {
  13. t.Fatal(err)
  14. }
  15. body, err := ioutil.ReadAll(res.Body)
  16. res.Body.Close()
  17. if err != nil {
  18. t.Fatal(err)
  19. }
  20. exp := "Before...Hello World...After"
  21. if exp != string(body) {
  22. t.Fatalf("Expected %s got %s", exp, body)
  23. }
  24. }

Exercises

  1. Create another piece of middleware that mutates the status of the request.
  2. Create a POST request and test that the request is properly handled.