From 9d0bee43729ae1e09dc6c8d0759a2de9011cc7f1 Mon Sep 17 00:00:00 2001 From: Danny van Kooten Date: Sun, 15 Jan 2017 16:12:14 +0100 Subject: [PATCH] add test for respond func --- api/api.go | 3 ++- api/api_test.go | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/api/api.go b/api/api.go index 9128a1b..1536e34 100644 --- a/api/api.go +++ b/api/api.go @@ -20,7 +20,8 @@ type envelope struct { func respond(w http.ResponseWriter, d interface{}) { w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) - enc.Encode(d) + err := enc.Encode(d) + checkError(err) } // log fatal errors diff --git a/api/api_test.go b/api/api_test.go index 568cb97..db4580b 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -1,7 +1,9 @@ package api import ( + "encoding/json" "net/http" + "net/http/httptest" "testing" ) @@ -62,3 +64,21 @@ func TestParseMajorMinor(t *testing.T) { t.Errorf("Return value should be %s is %s instead", expected, actual) } } + +func TestRespond(t *testing.T) { + w := httptest.NewRecorder() + respond(w, 15) + + // assert json header + if w.Header().Get("Content-Type") != "application/json" { + t.Errorf("Invalid Content-Type header") + } + + // assert json response + var d int + err := json.NewDecoder(w.Body).Decode(&d) + if err != nil { + t.Errorf("Invalid response body: %s", err) + } + +}