Skip to content

Commit

Permalink
add unit test for home handler
Browse files Browse the repository at this point in the history
  • Loading branch information
nothinux committed Feb 9, 2021
1 parent e6e4e90 commit 120314d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 10 deletions.
12 changes: 3 additions & 9 deletions cmd/web/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,14 @@ import (
"github.com/nothinux/karsajobs/pkg/models"
)

func (app *application) home(w http.ResponseWriter, r *http.Request) {
func home(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}

out, err := json.Marshal("")
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}

w.Header().Add("Content-type", "application/json")
w.Write(out)
w.Header().Add("Content-type", "text/plain")
w.Write([]byte("Up!"))
}

func (app *application) getJobs(w http.ResponseWriter, r *http.Request) {
Expand Down
27 changes: 27 additions & 0 deletions cmd/web/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,33 @@ import (
"github.com/nothinux/karsajobs/pkg/models"
)

func TestHomeHandler(t *testing.T) {
r, err := http.NewRequest(http.MethodGet, "/", nil)
if err != nil {
t.Fatal(err)
}

rr := httptest.NewRecorder()

http.HandlerFunc(home).ServeHTTP(rr, r)
result := rr.Result()
defer result.Body.Close()

if result.StatusCode != http.StatusOK {
t.Errorf("got %v, want %v", result.StatusCode, http.StatusOK)
}

body, err := ioutil.ReadAll(result.Body)
if err != nil {
t.Fatal(err)
}

if !reflect.DeepEqual(string(body), "Up!") {
t.Errorf("got %v, want %v", string(body), "Up!")
}

}

func TestGetJobsHandler(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
Expand Down
2 changes: 1 addition & 1 deletion cmd/web/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func (app *application) routes() http.Handler {
AllowedMethods: []string{"GET", "POST", "DELETE"},
}))

mux.Get("/", app.home)
mux.Get("/", home)
mux.Get("/jobs", app.getJobs)
mux.Get("/job/{id}", app.getJob)
mux.Post("/job", app.InsertJob)
Expand Down

0 comments on commit 120314d

Please sign in to comment.