Skip to content

Instantly share code, notes, and snippets.

@xr1337
Created February 18, 2020 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xr1337/5dbcfb936a21295bf7336bb8acbec28b to your computer and use it in GitHub Desktop.
Save xr1337/5dbcfb936a21295bf7336bb8acbec28b to your computer and use it in GitHub Desktop.
Syasa's 404 test
package main
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/pkg/errors"
)
var APIRequestNotFound = errors.New("Resource does not exist (404).")
var APIResponseInvalidStatusCode = errors.New("Response was invalid")
// API Class that talks to a third party service
type API struct {
client *http.Client
}
func NewAPI(client *http.Client) *API {
api := &API{client: client}
return api
}
// API method that makes a request to the third party service
func (a *API) MakeRequest(url string) ([]byte, error) {
resp, err := a.client.Get(url)
if err != nil {
return nil, errors.Wrap(err, "Failed to sent request")
}
if resp.StatusCode == 404 {
return nil, APIRequestNotFound
}
validResponse := resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices
if !validResponse {
return nil, APIResponseInvalidStatusCode
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
return body, err
}
// Unit test code
func TestInvalidRequestShouldReturnNotFoundError(t *testing.T) {
// 1. Create a mock server object that returns 404
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusNotFound)
}))
defer server.Close()
// 2. Initilize the object
sut := NewAPI(server.Client())
if sut == nil {
t.Fatalf("Failed to create sut")
}
// 3. Make a request
got, err := sut.MakeRequest(server.URL)
// 4. Assert if reponse body is not empty
if len(got) > 0 {
t.Fatalf("Expected empty body, got body size <%d>", len(got))
}
// 5. Assert that the returned error is not RequestNotFound
if err != APIRequestNotFound {
t.Fatalf("Expected <%s>, got <%s>", APIRequestNotFound, err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment