Add lesson 6: Testing handlers
3 changed files with 49 additions and 0 deletions
lessons/06-testing-handlers/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 6: Testing handlers | |
| 2 | + | |
| 3 | +Testing handlers comes up in almost every real Go project. We start with the why, then write code together. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/go-apis/lessons/6](https://glibcode.net/courses/go-apis/lessons/6) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `hello_test.go`: testing a handler with httptest (run: go test) | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +go test | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/06-testing-handlers/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 6 | |
| 2 | + | |
| 3 | +1. Look up one function or command the example uses in the official documentation. Note one option you didn't know. | |
| 4 | +2. Add a comment above each block explaining what it does, in your own words. | |
| 5 | +3. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to? | |
lessons/06-testing-handlers/hello_test.go ADDED
| @@ -0,0 +1,25 @@ | ||
| 1 | +package hello | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "fmt" | |
| 5 | + "net/http" | |
| 6 | + "net/http/httptest" | |
| 7 | + "testing" | |
| 8 | +) | |
| 9 | + | |
| 10 | +func hello(w http.ResponseWriter, r *http.Request) { | |
| 11 | + fmt.Fprintf(w, "Hello, %s!\n", r.URL.Query().Get("name")) | |
| 12 | +} | |
| 13 | + | |
| 14 | +func TestHello(t *testing.T) { | |
| 15 | + req := httptest.NewRequest("GET", "/hello?name=Go", nil) | |
| 16 | + rec := httptest.NewRecorder() | |
| 17 | + hello(rec, req) | |
| 18 | + | |
| 19 | + if rec.Code != http.StatusOK { | |
| 20 | + t.Fatalf("status = %d", rec.Code) | |
| 21 | + } | |
| 22 | + if got := rec.Body.String(); got != "Hello, Go!\n" { | |
| 23 | + t.Errorf("body = %q", got) | |
| 24 | + } | |
| 25 | +} | |