Permalink
Switch branches/tags
Nothing to show
Find file Copy path
33530a9 Oct 17, 2017
1 contributor

Users who have contributed to this file

93 lines (69 sloc) 1.82 KB
package main
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"testing"
)
func TestGetBirdsHandler(t *testing.T) {
birds = []Bird{
{"sparrow", "A small harmless bird"},
}
req, err := http.NewRequest("GET", "", nil)
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
hf := http.HandlerFunc(getBirdHandler)
hf.ServeHTTP(recorder, req)
if status := recorder.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
expected := Bird{"sparrow", "A small harmless bird"}
b := []Bird{}
err = json.NewDecoder(recorder.Body).Decode(&b)
if err != nil {
t.Fatal(err)
}
actual := b[0]
if actual != expected {
t.Errorf("handler returned unexpected body: got %v want %v", actual, expected)
}
}
func TestCreateBirdsHandler(t *testing.T) {
birds = []Bird{
{"sparrow", "A small harmless bird"},
}
form := newCreateBirdForm()
req, err := http.NewRequest("POST", "", bytes.NewBufferString(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(form.Encode())))
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
hf := http.HandlerFunc(createBirdHandler)
hf.ServeHTTP(recorder, req)
if status := recorder.Code; status != http.StatusFound {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
expected := Bird{"eagle", "A bird of prey"}
if err != nil {
t.Fatal(err)
}
actual := birds[1]
if actual != expected {
t.Errorf("handler returned unexpected body: got %v want %v", actual, expected)
}
}
func newCreateBirdForm() *url.Values {
form := url.Values{}
form.Set("species", "eagle")
form.Set("description", "A bird of prey")
return &form
}