Skip to content

Commit

Permalink
Unit test the index handler
Browse files Browse the repository at this point in the history
  • Loading branch information
dolph committed Apr 26, 2017
1 parent 5a896f8 commit bee5873
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
6 changes: 4 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ import (
)

func init() {
http.HandleFunc("/", handler)
http.HandleFunc("/", IndexHandler)
}

func handler(w http.ResponseWriter, r *http.Request) {
func IndexHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, "a plaintext pastebin service")
}

Expand Down
28 changes: 26 additions & 2 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
package main

import "testing"
import (
"testing"
"net/http"
"net/http/httptest"
)

func TestTrivial(t *testing.T) {
func TestIndexHandler(t *testing.T) {
request, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}

response := httptest.NewRecorder()
http.HandlerFunc(IndexHandler).ServeHTTP(response, request)

if status := response.Code; status != http.StatusOK {
t.Errorf(
"Handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}

expected_body := "a plaintext pastebin service"
if response.Body.String() != expected_body {
t.Errorf(
"Handler returned unexpected body: got %v want %v",
response.Body.String(), expected_body)
}
}

0 comments on commit bee5873

Please sign in to comment.