Skip to content

Commit

Permalink
adding tests
Browse files Browse the repository at this point in the history
  • Loading branch information
SartajBhuvaji committed Nov 22, 2024
1 parent 5e41670 commit 0635cd4
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions tests/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package api_test

import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"

"github.com/SartajBhuvaji/api"
)

func TestShortenURLHandler(t *testing.T) {
// create a request body
reqBody := map[string]string{"url": "https://www.sartaj.me"}
reqBytes, err := json.Marshal(reqBody)
if err != nil {
t.Fatalf("could not marshal JSON: %v", err)
}

// create a request
req, err := http.NewRequest(http.MethodPost, "/shorten", bytes.NewBuffer(reqBytes))
if err != nil {
t.Fatalf("could not create request: %v", err)
}

// create a response recorder
rec := httptest.NewRecorder()

// call the handler
http.HandlerFunc(api.ShortenURLHandler).ServeHTTP(rec, req)

// check the status code
if rec.Code != http.StatusOK {
t.Errorf("expected status OK; got %v", rec.Code)
}

// check the response body
var respBody map[string]string
if err := json.NewDecoder(rec.Body).Decode(&respBody); err != nil {
t.Fatalf("could not decode JSON: %v", err)
}

if _, ok := respBody["short_url"]; !ok {
t.Fatalf("response body does not have short_url field")
}
}

0 comments on commit 0635cd4

Please sign in to comment.