Last active
December 30, 2015 18:09
-
-
Save lateefj/7865577 to your computer and use it in GitHub Desktop.
MockHttp test.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"net/http" | |
"testing" | |
) | |
type MockResponse struct { | |
bytes.Buffer | |
Head http.Header | |
StatusCode int | |
} | |
func (mr *MockResponse) Header() http.Header { | |
return mr.Head | |
} | |
func (mr *MockResponse) WriteHeader(code int) { | |
mr.StatusCode = code | |
} | |
type MockTestResponse struct { | |
MockResponse | |
T *testing.T | |
} | |
// AssertBody ... Wrapper to provide an typing savings | |
func (mtr *MockTestResponse) Body(b string) { | |
if mtr.String() != b { | |
mtr.T.Fatalf("Response body is %s asserted that it is %s", mtr.String(), b) | |
} | |
} | |
// AssertCode ... Wrapper to provide an typing savings | |
func (mtr *MockTestResponse) Code(c int) { | |
if mtr.StatusCode != c { | |
mtr.T.Fatalf("Response StatusCode is %d asserted that it is %d", mtr.StatusCode, c) | |
} | |
} | |
func (mtr *MockTestResponse) Headers(t *testing.T, expectedHeaders map[string]string) { | |
if len(expectedHeaders) != len(mtr.Head) { | |
mtr.T.Fatalf("expected %v headers; got %v. Returned headers: %v", len(expectedHeaders), len(mtr.Head), mtr.Head) | |
} | |
for key, _ := range expectedHeaders { | |
if val := mtr.Head.Get(key); val != expectedHeaders[key] { | |
mtr.T.Fatalf("expected header %v to be '%v'; got '%v'", key, expectedHeaders[key], val) | |
} | |
} | |
} | |
func NewMockTestResponse(t *testing.T) *MockTestResponse { | |
return &MockTestResponse{MockResponse: MockResponse{Buffer: *bytes.NewBufferString(""), Head: http.Header{}, StatusCode: 200}, T: t} | |
} | |
func HomeHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "HomeHandler") | |
} | |
func TestHome(t *testing.T) { | |
req, _ := http.NewRequest("GET", "/path/to/handler", nil) | |
resp := NewMockTestResponse(t) | |
HomeHandler(resp, req) | |
resp.Body("HomeHandler") | |
resp.Code(200) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment