Unit Testing

Unit testing allows us to test a http.HandlerFunc directly without
running any middleware, routers, or any other type of code that might
otherwise wrap the function.

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. func HelloWorld(res http.ResponseWriter, req *http.Request) {
  7. fmt.Fprint(res, "Hello World")
  8. }
  9. func main() {
  10. http.HandleFunc("/", HelloWorld)
  11. http.ListenAndServe(":3000", nil)
  12. }

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. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. )
  7. func Test_HelloWorld(t *testing.T) {
  8. req, err := http.NewRequest("GET", "http://example.com/foo", nil)
  9. if err != nil {
  10. t.Fatal(err)
  11. }
  12. res := httptest.NewRecorder()
  13. HelloWorld(res, req)
  14. exp := "Hello World"
  15. act := res.Body.String()
  16. if exp != act {
  17. t.Fatalf("Expected %s gog %s", exp, act)
  18. }
  19. }

Exercises

  1. Change the output of HelloWorld to print a parameter and then test that the parameter is rendered.
  2. Create a POST request and test that the request is properly handled.